This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/website/contexts/UserContext.jsx

64 lines
1.8 KiB
React
Raw Normal View History

2020-08-03 12:04:07 +02:00
import { createContext, useState, useEffect } from 'react'
import Cookies from 'universal-cookie'
import api from '../utils/api'
2020-08-03 12:04:07 +02:00
const cookies = new Cookies()
2020-08-03 12:04:07 +02:00
export const UserContext = createContext()
2020-08-03 12:04:07 +02:00
function UserContextProvider (props) {
const [user, setUser] = useState(null)
const [isAuth, setIsAuth] = useState(false)
const [loginLoading, setLoginLoading] = useState(false)
const [messageLogin, setMessageLogin] = useState('')
2020-08-03 12:04:07 +02:00
useEffect(() => {
const newUser = cookies.get('user')
if (newUser != null) {
setIsAuth(true)
setUser(newUser)
}
}, [])
2020-08-03 12:04:07 +02:00
useEffect(() => {
if (isAuth) {
setMessageLogin('<p class="form-error"><b>Erreur:</b> Vous devez être déconnecter avant de vous connecter.</p>')
} 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('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>')
setLoginLoading(false)
} catch (error) {
setMessageLogin(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
setLoginLoading(false)
setIsAuth(false)
setUser(null)
}
2020-08-03 12:04:07 +02:00
}
2020-08-03 12:04:07 +02:00
return (
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, setMessageLogin }}>
{props.children}
</UserContext.Provider>
)
}
2020-08-03 12:04:07 +02:00
export default UserContextProvider