I have a React app connected to Firebase, i want to check if user is logged in at every page refresh, dispatching IS_SIGNED_IN
action, here's the action creator:
export function checkAuth() {
return dispatch => {
firebaseAuth().onAuthStateChanged((user) => {
if (user) {
dispatch(signedInAction())
} else {
dispatch(signedOutAction())
}
})
}
}
Inside the reducer i just make boolean isAuthenticated
to true/false:
case ActionTypes.isSignedIn: {
return Object.assign({}, state, {
isAuthenticated: true
})
}
case ActionTypes.isSignedOut: {
return Object.assign({}, state, {
isAuthenticated: false
})
}
Because i want to check if user is signed in when app loads i dispatch the action at componentDidMount
(which is wrong i guess):
class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
store.dispatch(checkAuth());
}
render() {
return (
<Provider store={store}>
<Router>
<Theme>
<Routes />
</Theme>
</Router>
</Provider>
);
}
}
This makes my code where i check for isAuthenticated
fail, because it's not yet set in the store, this is in Routes
component for example. What would be the best way to solve this? To add up, i know i can use conditional rendering and check to see when isAuthenticated
is defined, but i don't like that solution. Thoughts? Thanks