Search code examples
reactjsreact-routermern

react-router-dom-v6 change useHistory


const Routing=()=>{
  const Navigate=useNavigate()
  const {state,dispatch}=useContext(UserContext)
  useEffect(()=>{
    const user=JSON.parse(localStorage.getItem("user"))
    if(user){
      dispatch({type:"USER",payload:user})
    }
    else{
      if(!history.location.pathname.startsWith('/reset'))
           Navigate('/signin')
      }
    },[])

Since I am using react-dom-v6 , I know that I need to replace history.location.path.startsWith('/reset') with Navigate and I have seen posts but none is focused on this.

It would be really helpful if one can tell me!


Solution

  • Okay. it is wrong to use useNavigate in this case. you can use useLocation hook. Your code should be like this.

    const Routing = () => {
            const navigate = useNavigate();
            const location = useLocation();
            const { state, dispatch } = useContext(UserContext)
            useEffect(() => {
                const user = JSON.parse(localStorage.getItem("user"))
                if (user) {
                    dispatch({ type: "USER", payload: user })
                }
                else {
                    if (location.pathname.startsWith('/reset'))
                        navigate('/signin')
                }
            }, [])
    

    You can check out react router v6 https://reactrouter.com/docs/en/v6/getting-started/concepts#history-object