Files
grungnet/src/contexts/AuthContext.tsx

45 lines
1.2 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect, useContext } from "react";
import FakeStorage from "../helpers/FakeStorage";
2021-07-02 15:54:54 +10:00
type AuthContext = { password: string; setPassword: React.Dispatch<any> };
2020-04-14 16:05:44 +10:00
2021-06-03 15:31:18 +10:00
// TODO: check what default value we want here
const AuthContext = React.createContext<AuthContext | undefined>(undefined);
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 15:54:54 +10:00
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [password, setPassword] = useState<string>(
storage.getItem("auth") || ""
);
2020-04-14 16:05:44 +10:00
useEffect(() => {
storage.setItem("auth", password);
2020-04-14 16:05:44 +10: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 16:05:44 +10:00
export default AuthContext;