grungnet/src/contexts/AuthContext.js

40 lines
965 B
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
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(() => {
const storedUserId = localStorage.getItem("userId");
if (storedUserId) {
setUserId(storedUserId);
} else {
const id = shortid.generate();
setUserId(id);
localStorage.setItem("userId", id);
}
}, []);
2020-04-14 02:05:44 -04:00
const value = {
userId,
2020-04-14 02:05:44 -04:00
password,
setPassword,
authenticationStatus,
setAuthenticationStatus,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export default AuthContext;