Home > other >  useState not setting boolean value
useState not setting boolean value

Time:11-30

I am trying to set a boolean value with useState but its not working, i am not sure why? Basically i am using this as a Route component. when i console the loggedIn state after calling the function in the useEffect i keep getting false which is my initial value.

import React, {useState, useEffect} from 'react'
import axios from 'axios'
import { Navigate } from 'react-router-dom'

export default function AppLayout() {
const [loggedIn, setLoggedIn] = useState(false);

const isLoggedIn = () => {
const session_admin_item = window.localStorage.getItem("SESSION_ADMIN");
if(session_admin_item !== null){
 axios.get(`/api/authenticate/checktoken/${session_admin_item}`).then((res) => {
    if(res.data.message == "authenticated"){
      setLoggedIn(true);
    }
  });
} 


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

return (
loggedIn ? <Header />  :  <Navigate to="/login" />
)



}

Thank you in advance

CodePudding user response:

You should place hooks inside your function component

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

const isLoggedIn = () => {
    const [loggedIn, setLoggedIn] = useState(false);
    const session_admin_item = window.localStorage.getItem("SESSION_ADMIN");
    if(session_admin_item !== null){
    axios.get(`/api/authenticate/checktoken/${session_admin_item}`).then((res) => {
      if(res.data.message == "authenticated"){
        setLoggedIn(true);
    }

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

    return (/*Your jsx here*/)
  });
} 

CodePudding user response:

It seems that you missed the } at the end for AppLayout(). At the first glance, your code is not formatted, so I copied your code in VS code.

Try use built-in functions: Format Document or Format Document with in VS code.

CodePudding user response:

you missed a } of isLoggedIn() . I tried it on codesendbox with setTimeout and it is working fine check Here

  • Related