Home > Back-end >  How to detect history change action (back, forward, etc) in react-router-dom v6?
How to detect history change action (back, forward, etc) in react-router-dom v6?

Time:08-20

All I could find concerning listening to the location change is a code like:

const location = useLocation();
useEffect(() => {}, [location]);

But the issue I'm trying to solve is to understand whether the user went back or forward on the page, which the location object doesn't provide by itself.

My business requirement is to log out the user when they press "back" and the "back" page was a log in page which successfully logged the user in. I solved flagging the location via location.state to understand whether it's a post-successful-login route. Now I want to listen to the "back" action in the browser and emit the logout flow based on location.state.
If you have a better solution I'm all ears.

CodePudding user response:

If you only need to know how a user got to the current page then react-router-dom@6 has a useNavigationType hook that returns the type of navigation.

useNavigationType

declare function useNavigationType(): NavigationType;

type NavigationType = "POP" | "PUSH" | "REPLACE";

Example:

import { NavigationType, useNavigationType } from 'reat-router-dom';

...

const navigationType = useNavigationType();

...

switch (navigationType) {
  case NavigationType.POP:
    // back navigation

  case NavigationType.PUSH:
    // forward navigation

  case NavigationType.REPLACE:
    // redirection

  default:
    // ignore
}

Example:

import {
  NavigationType,
  useLocation,
  useNavigationType.
} from 'reat-router-dom';

...

const navigationType = useNavigationType();
const location = useLocation();

useEffect(() => {
  if (location.pathname === "/login" && navigationType === NavigationType.POP) {
    // dispatch logout action
  }
}, [location, navigationType]);

If you want to couple listening for navigation actions and calling a callback then consider something like this answer.

  • Related