Preload auth context with user data from SSR

This commit is contained in:
Maciej Ziarkowski 2021-02-17 22:43:04 +00:00
parent 2d53154a82
commit 17b83212c6
2 changed files with 14 additions and 6 deletions

View File

@ -54,7 +54,7 @@ export const App: React.FC<AppProps> = props => {
const mapAppPaths = ['/', '/:mode(view|edit|multi-edit)/:category/:building(\\d+)?/(history)?']; const mapAppPaths = ['/', '/:mode(view|edit|multi-edit)/:category/:building(\\d+)?/(history)?'];
return ( return (
<AuthProvider> <AuthProvider preloadedUser={props.user}>
<Switch> <Switch>
<Route exact path={mapAppPaths}> <Route exact path={mapAppPaths}>
<Header animateLogo={false} /> <Header animateLogo={false} />

View File

@ -45,11 +45,16 @@ export const AuthContext = createContext<AuthContextState>({
const noop = () => {}; const noop = () => {};
export const AuthProvider: React.FC = ({ interface AuthProviderProps {
children preloadedUser?: User;
}
export const AuthProvider: React.FC<AuthProviderProps> = ({
children,
preloadedUser
}) => { }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false); const [isAuthenticated, setIsAuthenticated] = useState(preloadedUser != undefined);
const [user, setUser] = useState<User>(undefined); const [user, setUser] = useState<User>(preloadedUser);
const [userError, setUserError] = useState<string>(undefined); const [userError, setUserError] = useState<string>(undefined);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@ -178,7 +183,10 @@ export const AuthProvider: React.FC = ({
// update user data initially to check if already logged in // update user data initially to check if already logged in
useEffect(() => { useEffect(() => {
updateUserData(); // if user state not preloaded
if(user == undefined) {
updateUserData();
}
}, []); }, []);
return ( return (