You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Mobile/ctx.tsx

43 lines
982 B

import React from "react";
import { User } from "./model/User";
import { useStorageState } from "./useStorageState";
const AuthContext = React.createContext<{
signIn: (user: User) => void;
signOut: () => void;
session?: User | null;
isLoading: boolean;
}>({
signIn: () => null,
signOut: () => null,
session: null,
isLoading: false,
});
export function useSession() {
return React.useContext(AuthContext);
}
export function SessionProvider(props: Readonly<React.PropsWithChildren>) {
const [[isLoading, sessionStr], setSessionStr] = useStorageState("session");
const session = sessionStr ? User.fromJSON(JSON.parse(sessionStr)) : null;
return (
<AuthContext.Provider
value={{
signIn: (user: User) => {
setSessionStr(JSON.stringify(user));
},
signOut: () => {
setSessionStr(null);
},
session,
isLoading,
}}
>
{props.children}
</AuthContext.Provider>
);
}