import { useRouter } from "next/router"; import { createContext, useContext, useEffect, useRef, useState } from "react"; import ReconnectingWebSocket from "reconnecting-websocket"; import { getUser, loginRequest, logoutRequest, } from "../requests/requests.users.js"; import { notificationService } from "../services/notification.service.js"; import { isBrowser } from "../utils/utils.js"; export const SessionContext = createContext({ isLogin: false, login: () => {}, logout: () => {}, authData: {}, }); export const useSessionContext = () => { return useContext(SessionContext); }; export const SessionProvider = ({ children }) => { const [authData, setAuthData] = useState(); const [isLogin, setLogin] = useState( isBrowser && localStorage.getItem("token") !== null ); useEffect(() => { setLogin(isBrowser && localStorage.getItem("token") !== null); }, []); const router = useRouter(); const login = (token) => { //data = {username: "", password1: "", password2: ""} localStorage.clear(); localStorage.setItem("token", token); setLogin(true); }; const logout = () => { if (localStorage.getItem("token") !== null) { logoutRequest(localStorage.getItem("token")) .then(() => { localStorage.setItem("token", null); if (router.route == "/dashboard") { router.push("/login"); } }) .then((res) => { setAuthData({}); setLogin(false); notificationService.success( "Déconnexion", "Vous n'êtes plus connecté !", { keepAfterRouteChange: true } ); }) .catch((err) => { notificationService.error( "Déconnexion", "Erreur lors de la déconnexion !", { keepAfterRouteChange: true } ); }); } }; useEffect(() => { if (localStorage.getItem("token") != null) { getUser() .then((res) => { setAuthData(res); }) .catch((err) => { localStorage.clear(); }); } else { setAuthData({}) } }, [isBrowser && localStorage.getItem("token")]); return ( {children} ); };