The problem I'm running into is that currentUser in App.js is null when <PrivateRoute /> renders, which will cause it to render a <Redirect /> and navigate to /login.
However, if I view the React Dev Tools I can see that the value field in Context.Provider does correctly have a user object set.This prop should rerender the rest of the app but it does not.
Why doesn't currentUser updating update the routes?
Auth.js
import React, { useEffect, useState } from 'react';
import firebase from 'firebase';
export const AuthContext = React.createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
firebase.auth().onAuthStateChanged(setCurrentUser);
}, []);
return (
<AuthContext.Provider value={{ currentUser }}>
{children}
</AuthContext.Provider>
);
};
App.js
import { AuthProvider } from './Auth';
import { AuthContext } from './Auth';
function App() {
const PrivateRoute = ({ component: Component, ...rest }) => {
const { currentUser } = useContext(AuthContext);
return (
<Route
{...rest}
render={props =>
currentUser ? (
<Component {...props} {...rest} />
) : (
<Redirect to={{ pathname: '/login' }} />
)
}
/>
);
};
return (
<AuthProvider>
<Router history={createBrowserHistory()}>
<Switch>
<PrivateRoute path="/" exact component={HomeScreen} />
<Route path="/login" exact component={LogIn} />
</Switch>
</Router>
</AuthProvider>
);
}