import { createContext, useState, useEffect } from 'react' import Cookies from 'universal-cookie' import api from '../utils/api' const cookies = new Cookies() export const UserContext = createContext() function UserContextProvider (props) { const [user, setUser] = useState(null) const [isAuth, setIsAuth] = useState(false) const [loginLoading, setLoginLoading] = useState(false) const [messageLogin, setMessageLogin] = useState('') useEffect(() => { const newUser = cookies.get('user') if (newUser != null) { setIsAuth(true) setUser(newUser) } }, []) useEffect(() => { if (isAuth) { setMessageLogin( '

Erreur: Vous devez être déconnecter avant de vous connecter.

' ) } else { setMessageLogin('') } }, [isAuth]) const logoutUser = () => { cookies.remove('user', { path: '/' }) setUser(null) setIsAuth(false) } const loginUser = async ({ email, password }) => { setLoginLoading(true) try { const response = await api.post('/users/login', { email, password }) const newUser = response.data cookies.remove('user', { path: '/' }) cookies.set('user', newUser, { path: '/', maxAge: newUser.expiresIn }) setUser(newUser) setIsAuth(true) setMessageLogin( '

Succès: Connexion réussi!

' ) setLoginLoading(false) } catch (error) { setMessageLogin( `

Erreur: ${error.response.data.message}

` ) setLoginLoading(false) setIsAuth(false) setUser(null) } } return ( {props.children} ) } export default UserContextProvider