2024-03-05 02:18:30 +03:00
|
|
|
import { useCallback, useMemo } from "react";
|
2023-12-31 16:35:15 +03:00
|
|
|
import { useLocation, useNavigate } from "react-router-dom";
|
|
|
|
|
|
2024-03-05 02:18:30 +03:00
|
|
|
export default function useOverlayState(
|
|
|
|
|
key: string,
|
|
|
|
|
): [string | undefined, (value: string, replace?: boolean) => void] {
|
2023-12-31 16:35:15 +03:00
|
|
|
const location = useLocation();
|
|
|
|
|
const navigate = useNavigate();
|
|
|
|
|
const currentLocationState = location.state;
|
|
|
|
|
|
|
|
|
|
const setOverlayStateValue = useCallback(
|
2024-03-05 02:18:30 +03:00
|
|
|
(value: string, replace: boolean = false) => {
|
2023-12-31 16:35:15 +03:00
|
|
|
const newLocationState = { ...currentLocationState };
|
|
|
|
|
newLocationState[key] = value;
|
2024-03-05 02:18:30 +03:00
|
|
|
navigate(location.pathname, { state: newLocationState, replace });
|
2023-12-31 16:35:15 +03:00
|
|
|
},
|
2024-02-29 01:23:56 +03:00
|
|
|
// we know that these deps are correct
|
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
|
[key, navigate],
|
2023-12-31 16:35:15 +03:00
|
|
|
);
|
|
|
|
|
|
2024-03-05 02:18:30 +03:00
|
|
|
const overlayStateValue = useMemo<string | undefined>(
|
|
|
|
|
() => location.state && location.state[key],
|
|
|
|
|
[location, key],
|
|
|
|
|
);
|
|
|
|
|
|
2023-12-31 16:35:15 +03:00
|
|
|
return [overlayStateValue, setOverlayStateValue];
|
|
|
|
|
}
|