grungnet/src/contexts/AuthContext.js

72 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-04-14 02:05:44 -04:00
import React, { useState, useEffect } from "react";
import shortid from "shortid";
2020-04-14 02:05:44 -04:00
import { getRandomMonster } from "../helpers/monsters";
import db from "../database";
2020-04-14 02:05:44 -04:00
const AuthContext = React.createContext();
export function AuthProvider({ children }) {
const [password, setPassword] = useState(
sessionStorage.getItem("auth") || ""
);
useEffect(() => {
sessionStorage.setItem("auth", password);
}, [password]);
const [authenticationStatus, setAuthenticationStatus] = useState("unknown");
const [userId, setUserId] = useState();
useEffect(() => {
async function loadUserId() {
const storedUserId = await db.table("user").get("userId");
if (storedUserId) {
setUserId(storedUserId.value);
} else {
const id = shortid.generate();
setUserId(id);
db.table("user").add({ key: "userId", value: id });
}
}
loadUserId();
}, []);
const [nickname, setNickname] = useState("");
useEffect(() => {
async function loadNickname() {
const storedNickname = await db.table("user").get("nickname");
if (storedNickname) {
setNickname(storedNickname.value);
} else {
const name = getRandomMonster();
setNickname(name);
db.table("user").add({ key: "nickname", value: name });
}
}
loadNickname();
}, []);
useEffect(() => {
if (nickname !== undefined) {
db.table("user").update("nickname", { value: nickname });
}
}, [nickname]);
2020-04-14 02:05:44 -04:00
const value = {
userId,
nickname,
setNickname,
2020-04-14 02:05:44 -04:00
password,
setPassword,
authenticationStatus,
setAuthenticationStatus,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export default AuthContext;