User Context (#51)

* feat(frontend): user Context / useUser hook

Adds a UserContext to wrap the app and load/cache the user when the website renders. Also adds the
useUser hook to pull in user data anywhere its needed on the site. This commit also adds redirection
to the login page for users who are not signed in

* fix(frontend): use process.env.PORT for user request on server side (defaults to 3000)

* docs(frontend): added documentation/notes for how the user context/login works
This commit is contained in:
sct
2020-09-05 13:16:26 +09:00
committed by GitHub
parent 350af66129
commit 190a8831c7
7 changed files with 173 additions and 14 deletions

View File

@@ -0,0 +1,28 @@
import React, { useEffect } from 'react';
import { User, useUser } from '../hooks/useUser';
import { useRouter } from 'next/dist/client/router';
interface UserContextProps {
initialUser: User;
}
/**
* This UserContext serves the purpose of just preparing the useUser hooks
* cache on server side render. It also will handle redirecting the user to
* the login page if their session ever becomes invalid.
*/
export const UserContext: React.FC<UserContextProps> = ({
initialUser,
children,
}) => {
const { user } = useUser({ initialData: initialUser });
const router = useRouter();
useEffect(() => {
if (!router.pathname.match(/(setup|login)/) && !user) {
router.push('/login');
}
}, [router, user]);
return <>{children}</>;
};