-
Hey, I'm using the BrowserRouter with jotai to store state in the hash: https://jotai.org/docs/extensions/location#atomwithhash. It was working well until some pages needed to be opened with some state. Eg: <BrowserRouter>
<Routes>
<Route index element={<Index />} />
<Route path="somewhere" element={<RouteWithState />} />
</Routes>
</BrowserRouter> and: const countAtom = atomWithHash<number>("count", 0);
function RouteWithState() {
const { state } = useLocation();
const [count, setCount] = useAtom(countAtom);
return (
<>
<h1>Route with state</h1>
<p>State is: {JSON.stringify(state)}</p>
<p>
Count is: {count}{" "}
<button onClick={() => setCount((count) => count + 1)}>+</button>
</p>
</>
);
} What happens is that whenever the page sets the value of an atom with hash, the state in the location is lost Is that a limitation of react-router (does it consider that we're doing a fresh navigation when the hash changes?) or is there anything I need to change to make it work? Sandbox here: https://codesandbox.io/p/sandbox/router-jotai-kkg75p?file=%2Fsrc%2FApp.tsx%3A2%2C65 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
OK I think I found the solution, thanks to jotaijs/jotai-location#4: - const countAtom = atomWithHash<number>("count", 0);
+ const countAtom = atomWithHash<number>("count", 0, { setHash: "replaceState" }); This way, the state is not reset when the hash changes. See fixed sandbox: https://codesandbox.io/p/sandbox/router-jotai-forked-pj8nd8 |
Beta Was this translation helpful? Give feedback.
OK I think I found the solution, thanks to jotaijs/jotai-location#4:
This way, the state is not reset when the hash changes. See fixed sandbox: https://codesandbox.io/p/sandbox/router-jotai-forked-pj8nd8