I have the following problem. I need to set the state of the app component after the onSnapshot event. That's why I have put that in the componentDidMount() and it works fine it logs the set user, however when I put the same code in a useEffect with an empty dependency array it logs null. Any ideas?
Here are the two components:
Class
class App extends Component<{}, AppState> {
constructor(props: any) {
super(props);
this.state = {
currentUser: undefined,
};
}
unsubscribeFromAuth = () => {};
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDoc(userAuth);
userRef?.onSnapshot((snapShot) => {
this.setState({
currentUser: {
id: snapShot.id,
...snapShot.data(),
},
});
console.log(this.state);
});
}
});
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render() {
return (
<div>
<Header currentUser={this.state.currentUser} />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/shop" component={ShopPage} />
<Route path="/signin" component={SignInUpPage} />
</Switch>
</div>
);
}
}
Functional
function App() {
const [currentUser, setCurrentUser] = useState<User | null>(null);
useEffect(() => {
let unsubscribeFromAuth = () => {};
const afterMount = () => {
unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDoc(userAuth);
userRef?.onSnapshot((snapShot) => {
setCurrentUser({
id: snapShot.id,
...snapShot.data(),
});
console.log(currentUser);
});
}
});
};
afterMount();
return () => {
unsubscribeFromAuth();
};
}, []);
return (
<div>
<Header currentUser={currentUser} />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/shop" component={ShopPage} />
<Route path="/signin" component={SignInUpPage} />
</Switch>
</div>
);
}
export default App;