'setState not working inside useEffect hook and token is showing null everytime

I am building a wrapper which will see if token is present or not in the localstorage then it will render the component otherwise redirect the user to the login page. The auth and token state are not getting changed...

import Home from "./Home";
import { Redirect } from "react-router-dom";
import { useEffect, useState } from "react";

function Protected_home() {
    const[token , setToken] = useState(null)
    const [auth,setAuth] = useState(false)

    useEffect(()=>{
        setToken(localStorage.getItem("noty__auth__token")) //not working
        console.log("token fetched") // getting a log the token
    },[])

    useEffect(()=>{
        setAuth(true) // setting auth to true
    },[token])

    useEffect(()=>{
        alert(token) // getting null
    },[auth])

    // conditional rendering of the components
    if(auth){
        return <Home/>
    }else{
        return <Redirect to={{pathname:"/"}}/>
    }
}

export default Protected_home


Solution 1:[1]

you should setItem in localsotorage and then use getItem method if you've done setting the value check your browser storage to see is there any data or not. check this thing out too

 useEffect(()=>{
     const data = localStorage.getItem("noty__auth__token");
     if(data) setToken(data)
    },[])

Solution 2:[2]

Trying giving the conditions before setting state. As on first render every useEffect will be called unlike of dependency array.

import "./styles.css";
import { Redirect } from "react-router-dom";
import { useEffect, useState } from "react";

export default function App() {
  const [token, setToken] = useState(null);
  const [auth, setAuth] = useState(false);

  useEffect(() => {
    console.log("chek");
    const data = localStorage.getItem("noty__auth__token");
    if (data) {
      setToken(data); //not working
      console.log("token fetched");
    } // getting a log the token
  }, []);

  useEffect(() => {
    console.log("auth");
    if (token) {
      setAuth(true);
    } // setting auth to true
  }, [token]);

  useEffect(() => {
    console.log("alert");
    //alert(token); // getting null
  }, [auth]);

  // conditional rendering of the components
  if (auth) {
    return <h1>welcomehome</h1>;
  } else {
    return <h2>hey</h2>;
  }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eisa Rezaei
Solution 2 sai manoj