Home > OS >  setState not working inside useEffect hook and token is showing null everytime
setState not working inside useEffect hook and token is showing null everytime

Time:04-27

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

CodePudding user response:

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)
    },[])

CodePudding user response:

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>;
  }

}
  • Related