2023-06-04 04:28:07 +02:00
|
|
|
import React, { useState, createContext } from "react";
|
2023-10-06 00:16:14 +02:00
|
|
|
import { AUTH_TIMESTAMP, AUTH_TOKEN, AUTH_USER } from "./utils/constants";
|
2023-06-04 04:28:07 +02:00
|
|
|
|
|
|
|
export const AuthContext = createContext(null);
|
|
|
|
export function ContextWrapper(props) {
|
2023-07-25 19:37:04 +02:00
|
|
|
const localUser = localStorage.getItem(AUTH_USER);
|
|
|
|
const localAuthToken = localStorage.getItem(AUTH_TOKEN);
|
2023-06-04 04:28:07 +02:00
|
|
|
const [store, setStore] = useState({
|
|
|
|
user: localUser ? JSON.parse(localUser) : null,
|
|
|
|
authToken: localAuthToken ? localAuthToken : null,
|
|
|
|
});
|
|
|
|
|
|
|
|
const [actions] = useState({
|
|
|
|
updateUser: (user, authToken = "") => {
|
2023-07-25 19:37:04 +02:00
|
|
|
localStorage.setItem(AUTH_USER, JSON.stringify(user));
|
|
|
|
localStorage.setItem(AUTH_TOKEN, authToken);
|
2023-06-04 04:28:07 +02:00
|
|
|
setStore({ user, authToken });
|
|
|
|
},
|
|
|
|
unsetUser: () => {
|
2023-07-25 19:37:04 +02:00
|
|
|
localStorage.removeItem(AUTH_USER);
|
|
|
|
localStorage.removeItem(AUTH_TOKEN);
|
2023-10-06 00:16:14 +02:00
|
|
|
localStorage.removeItem(AUTH_TIMESTAMP);
|
2023-06-04 04:28:07 +02:00
|
|
|
setStore({ user: null, authToken: null });
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return (
|
|
|
|
<AuthContext.Provider value={{ store, actions }}>
|
|
|
|
{props.children}
|
|
|
|
</AuthContext.Provider>
|
|
|
|
);
|
|
|
|
}
|