Redirect in Reat JS

I am trying to redirect the route when the condition is true. I used ‘useNavigate’ in react-router-dom. But it’s not working.

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
 if (localStorage.getItem('bearerToken') == null) {
      console.log("true condition");

Console data is printed but not redirected.

>Solution :

I suppose you could add this check to an effect (useEffect). Currently you are checking for an item in local storage outside of an effect.

With React, you have to set-aside some things you’ve learned with vanilla JavaScript and make yourself think-in-React. It makes sense to just do an if check in your component, but you need to explicitly tell React you want to check for something, whether that be an API call or checking local storage and doing something based on that result.

useEffect(() => {
  // check if "bearerToken" has NOT been set in local storage
  if (!localStorage.getItem("bearerToken")) {
    console.log("true condition");
    // it hasn't! let's navigate back to the home page
// 👇 this is a dependency array. 
// it tells the effect to run
// if any item in it has changed.
// (we don't have any dependencies
// so we can leave it empty. 
}, []);

This will check if the item is not in local storage. If it’s not, it will redirect you back to the home page.

Leave a Reply