pashto-grammar/src/user-context.tsx

40 lines
989 B
TypeScript
Raw Normal View History

2021-09-18 13:11:08 +00:00
import React, { useState, createContext, useEffect } from "react"
import { AT, getUser } from "@lingdocs/lingdocs-main";
2021-09-18 04:43:00 +00:00
const UserContext = createContext<
2021-09-18 13:11:08 +00:00
{
user: AT.LingdocsUser | undefined,
setUser: React.Dispatch<React.SetStateAction<AT.LingdocsUser | undefined>>,
pullUser: () => void,
}
2021-09-18 04:43:00 +00:00
| undefined
>(undefined);
function UserProvider({ children }: any) {
const [user, setUser] = useState<AT.LingdocsUser | undefined>(undefined);
2021-09-18 13:11:08 +00:00
function pullUser() {
getUser().then((user) => {
setUser(user === "offline" ? undefined : user);
}).catch(console.error);
}
useEffect(() => {
pullUser();
}, []);
return <UserContext.Provider value={{ user, setUser, pullUser }}>
2021-09-18 04:43:00 +00:00
{children}
</UserContext.Provider>;
}
function useUser() {
const context = React.useContext(UserContext)
if (context === undefined) {
throw new Error('useCount must be used within a CountProvider')
}
return context;
}
export { UserProvider, useUser };