Reputation: 315
I am currently facing an issue where useEffect only works on the first render which in result of my button to log out does not work, or am I doing something incorrect with redirect hence the component will never reach dashboard causing it to not run useeffect ?
below is my current work so far.
App.js
import React from 'react'
import './App.css'
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import UserProvider from "./providers/UserProvider"
import SignIn from "./SignIn";
import Dashboard from './Dashboard'
import PrivateRoute from './components/PrivateRoute'
function App() {
return (
<UserProvider>
<Router>
<div className="App">
<Switch>
<PrivateRoute path="/Dashboard" component={Dashboard}/>
<Route path="/" component={SignIn}/>
</Switch>
</div>
</Router>
</UserProvider>
);
}
export default App;
Dashboard.js
import React, { useEffect, useContext, useState } from "react"
import { UserContext } from "./providers/UserProvider"
import { Redirect } from "react-router-dom"
import {logOut} from './config/firebase'
export default function Dashboard() {
const user = useContext(UserContext);
const [redirect, setredirect] = useState(null);
useEffect(() => {
console.log(user)
if (!user) {
setredirect("/");
}
}, [user]);
return (!redirect) ? (
<div>
<h1>Welcome Home</h1>
<button onClick={logOut}>
<img
src="https://img.icons8.com/ios-filled/50/000000/google-logo.png"
alt="google icon"
/>
<span> logout</span>
</button>
</div>
):
(<Redirect to={redirect} />);
}
firebase logout
export const logOut = () => {
auth.signOut().then(()=> {
console.log('logged out') // <-- sign out has no issue
}).catch((error) => {
console.log(error.message)
})
}
Findings : User context has been updated correctly, from my observation useEffect will only work on the initial rendering but not when logout button clicked (console.log will trigger, but useEffect does not)
Appreciate if anyone could point me to the right direction. Thank you.
Upvotes: 0
Views: 540
Reputation: 3010
you can have a user
state variable (to store user auth token) and mention that as the second argument in useEffect
.
Generally useEffect
runs after every render, but it’s also perfect for running some code in response to a state change. You can specify when should the effect runs by passing the second argument to useEffect
.
Think of the second argument as an array of “dependencies” – variables that, if changed, the effect should rerun. These can be any kind of variable: props, state, or anything else.
useEffect(() => {
console.log("user state changed", user);
}, [user]);
Upvotes: 1