diff --git a/src/useStickyState.ts b/src/useStickyState.ts new file mode 100644 index 0000000..5897b25 --- /dev/null +++ b/src/useStickyState.ts @@ -0,0 +1,17 @@ +import { useEffect, useState } from "react"; + +export default function useStickyState(defaultValue: T, key: string): [T, React.Dispatch>] { + + const [value, setValue] = useState(() => { + const stickyValue = window.localStorage.getItem(key); + return stickyValue !== null + ? JSON.parse(stickyValue) as T + : defaultValue; + }); + + useEffect(() => { + window.localStorage.setItem(key, JSON.stringify(value)); + }, [key, value]); + + return [value, setValue]; +} \ No newline at end of file diff --git a/src/user-context.tsx b/src/user-context.tsx index 9478f53..7df5308 100644 --- a/src/user-context.tsx +++ b/src/user-context.tsx @@ -1,4 +1,5 @@ -import React, { useState, createContext, useEffect } from "react" +import React, { createContext, useEffect } from "react" +import useStickyState from "./useStickyState"; import { AT, getUser } from "@lingdocs/lingdocs-main"; import { CronJob } from "cron"; @@ -13,12 +14,11 @@ const UserContext = createContext< // TODO: persisting user in local state function UserProvider({ children }: any) { - const [user, setUser] = useState(undefined); + const [value, setValue] = useStickyState(undefined, "saved-user"); function pullUser() { - console.log("pulling user..."); getUser().then((user) => { - setUser(user === "offline" ? undefined : user); + setValue(user === "offline" ? undefined : user); }).catch(console.error); } @@ -35,7 +35,7 @@ function UserProvider({ children }: any) { // eslint-disable-next-line }, []); - return + return {children} ; } @@ -43,7 +43,7 @@ function UserProvider({ children }: any) { function useUser() { const context = React.useContext(UserContext) if (context === undefined) { - throw new Error('useCount must be used within a CountProvider') + throw new Error('useUser must be used within a UserProvider') } return context; }