0

I have tried without setTimeout either console.log returns false false every time, initial value never changes. Can anyone help ?

import { useState, useEffect } from 'react';

const useAuth = () => {
    const [authenticated, setAuthenticated] = useState(false);
    const token = localStorage.getItem('token');

    useEffect(() => {
        if (token) {
            fetch('http://myapp.test/api/checkAuth', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${token}`,
                },
            })
                .then((response) => {
                    if (response.ok) {
                        console.log(authenticated);
                        setAuthenticated(true);
                        setTimeout(() => console.log(authenticated), 3000);
                    }
                })
                .catch(() => {

                });
        }
    },[]);
    return authenticated;
};

export default useAuth;

  • 2
    what happens if you add another useEffect for debugging the value. useEffect(()=>{console.log(authenticated);},[authenticated]); ? – programandoconro Apr 03 '23 at 00:37
  • Unrelated to your issue, but you should move `const token = localStorage.getItem('token');` into your useEffect before calling your service. For react components, it is generally bad practice to access DOM-only variables like this outside of a React lifecycle method/hook, can run into odd behavior. It may help to see how you are using this hook, could be getting rendered conditionally which is bad. – segFault Apr 03 '23 at 00:41

0 Answers0