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;