Home > OS >  If Token is not Present I want to redirect the page to login but its not working. When no token is p
If Token is not Present I want to redirect the page to login but its not working. When no token is p

Time:06-30

I am Using React Router Dom V6

Here if(!localStorage.getItem("token")){ navigate("/login") } is not Working

import React,{useState,useEffect} from 'react';
import axios from 'axios';

import { useNavigate } from 'react-router-dom';

const Home = (props) => {
  const [user,setUser]=useState(null);

  let navigate = useNavigate();
  const getUser=async()=>{                                   **Here i have access the token**
    const res=await axios.get("/auth",{
      headers:{
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
    });
    setUser(res.data);
  };

  useEffect(()=>{
    getUser();
  },[]);

  const logout=()=>{                     **I have removed the token here**
    localStorage.removeItem("token");
    navigate("/login");
  };

  if(!localStorage.getItem("token")){    //HERE IS NOT WORKING
    navigate("/login");
  }
  
  return (
    <div className="m-5">
      <div className="jumbotron">
        <p className="lead">Welcome {user && user.name}</p>
        <button className="btn btn-danger" onClick={logout}>Logout</button>
      </div>
    </div>
  )
}

export default Home       

CodePudding user response:

You can check this in the useEffect method if the token is there then getuser otherwise navigate to the login page

  useEffect(()=>{
  if(!localStorage.getItem("token")){
    navigate("/login");
  }else{
    getUser();
  }
  },[]);

CodePudding user response:

You shouldn't add your if statement outside of a function, as suggests this website. if statements can only be used outside of a function for conditional rendering (i.e. when the if statement returns something). When you want to check something only once, you should check it inside of useEffect. For your example, it should be:

useEffect(() => {
  getUser()
  if(!localStorage.getItem("token")) {
    navigate("/login");
  }
}, [])
  • Related