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)?'];
return (
<AuthProvider>
<AuthProvider preloadedUser={props.user}>
<Switch>
<Route exact path={mapAppPaths}>
<Header animateLogo={false} />

View File

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