store selected global relay in history

This commit is contained in:
Martti Malmi 2023-12-05 00:31:56 +02:00
parent 9af52bfefd
commit 3badcd0ab6
2 changed files with 52 additions and 2 deletions

View File

@ -0,0 +1,49 @@
import { useEffect, useRef, useState } from "react";
function useHistoryState(initialValue, key) {
const currentHistoryState = history.state ? history.state[key] : undefined;
const myInitialValue = currentHistoryState === undefined ? initialValue : currentHistoryState;
const [state, setState] = useState(myInitialValue);
const latestValue = useRef(state);
const setHistoryState = value => {
const newHistoryState = { ...history.state, [key]: value };
history.replaceState(newHistoryState, "");
latestValue.current = value;
};
useEffect(() => {
if (state !== latestValue.current) {
setHistoryState(state);
const newHistoryState = { ...history.state, [key]: state };
history.replaceState(newHistoryState, "");
latestValue.current = state;
}
// Cleanup logic
return () => {
if (state !== latestValue.current) {
const newHistoryState = { ...history.state, [key]: state };
history.replaceState(newHistoryState, ""); // Save the final state
}
};
}, [state, key]);
const popStateListener = event => {
if (event.state && key in event.state) {
setState(event.state[key]);
}
};
useEffect(() => {
window.addEventListener("popstate", popStateListener);
return () => {
window.removeEventListener("popstate", popStateListener);
};
}, []);
return [state, setState];
}
export default useHistoryState;

View File

@ -22,6 +22,7 @@ import TrendingHashtags from "@/Element/Trending/TrendingHashtags";
const InviteModal = lazy(() => import("@/Element/Invite"));
import messages from "./messages";
import useHistoryState from "@/Hooks/useHistoryState";
interface RelayOption {
url: string;
@ -61,8 +62,8 @@ const FollowsHint = () => {
export const GlobalTab = () => {
const { relays } = useLogin();
const [relay, setRelay] = useState<RelayOption>();
const [allRelays, setAllRelays] = useState<RelayOption[]>();
const [relay, setRelay] = useHistoryState<RelayOption>(undefined, "global-relay");
const [allRelays, setAllRelays] = useHistoryState<RelayOption[]>(undefined, "global-relay-options");
const [now] = useState(unixNow());
const system = useContext(SnortContext);