Can't get proper location state in React Router if location is added in Routes component

Viewed 478

I'm working with Framer Motion and React Router so I added location={location} in <Routes>. When I try to get location.state.from it just shows me the path that I am redirected to and not the previous path. When I remove location in <Routes> then it works properly.

App.js

<AnimatePresence exitBeforeEnter>
  <Routes key={location.pathname} location={location}>
    <Route element={<PublicWrapper />}>
      <Route path="/login" element={<Login />} />
    </Route>

    <Route element={<PrivateWrapper />}>
      <Route path="/tracker" element={<Tracker />} />
    </Route>
  </Routes>
</AnimatePresence>

Login.js

const location = useLocation();
const from = location.state?.from?.pathname;
console.log(from); // Returns '/login' even if user came from '/tracker'
1 Answers

Managed to solve it by getting the path inside PrivateWrapper component instead of Login component.

PrivateWrapper.js

const location = useLocation();
const { setFrom } = useContext(AuthContext);

useEffect(() => {
  setFrom(location.state.from.pathname);
}, [location.state, setFrom]);

Related