grungnet/src/contexts/AuthContext.tsx

48 lines
1.2 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect, useContext } from "react";
import FakeStorage from "../helpers/FakeStorage";
2021-07-17 04:39:49 -04:00
type AuthContextValue = {
2021-07-09 02:22:35 -04:00
password: string;
setPassword: React.Dispatch<React.SetStateAction<string>>;
};
2020-04-14 02:05:44 -04:00
2021-07-17 04:39:49 -04:00
const AuthContext =
React.createContext<AuthContextValue | undefined>(undefined);
2021-06-03 01:31:18 -04:00
let storage: Storage | FakeStorage;
try {
sessionStorage.setItem("__test", "__test");
sessionStorage.removeItem("__test");
storage = sessionStorage;
} catch (e) {
console.warn("Session storage is disabled, no authentication will be saved");
storage = new FakeStorage();
}
2021-07-02 01:54:54 -04:00
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [password, setPassword] = useState<string>(
storage.getItem("auth") || ""
);
2020-04-14 02:05:44 -04:00
useEffect(() => {
storage.setItem("auth", password);
2020-04-14 02:05:44 -04:00
}, [password]);
const value = {
password,
setPassword,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within a AuthProvider");
}
return context;
}
2020-04-14 02:05:44 -04:00
export default AuthContext;