I am using React Context to pass in the state and setState like this
const [authContext, setAuthData] = useState({
isAuthenticated: false,
userID:"-1",
email:"test",
name:"test"
});
<AuthContext.Provider value={[authContext,setAuthData]}>
<Router>
<NavbarMenu />
<div className="AllElements">
<Switch>
<Route exact path="/" component={HomePage} />
<Route component={Routes} />
</Switch>
</div>
</Router>
</AuthContext.Provider>
and in another component, I retrieve it like this
const [authContext, setAuthData ] = useContext(AuthContext);
const { isAuthenticated } = authContext;
I call setAuthData like this whenever I want to update authContext
const HomePage = () => {
if(data && data.login && data.login.token){
console.log("Data token exists");
setAuthData(() => [{
isAuthenticated: true,
userID:data.login.id,
email:data.login.email,
name:data.login.name
}]);
}
return (<div><p>test</p></div>);
};
export default HomePage;
However, once it hits setAuthData, everything inside the if {} gets called multiple times. I keep seeing multiple "Data token exists" in the console until it errors out to Maximum update depth exceeded