1 import axios from 'axios';
2 import { isEqual } from 'lodash';
3 import PropTypes from 'prop-types';
4 import React from 'react';
6 const context = React.createContext({
12 export const useUser = () => React.useContext(context);
14 export const withUser = (WrappedComponent, as) => function WithUserContext(props) {
15 return <context.Consumer>
16 {ctx => <WrappedComponent {...{[as || 'user']: ctx.user, ...props}} />}
20 export const UserProvider = ({ children }) => {
21 const [user, setUser] = React.useState(null);
23 const fetchUser = React.useCallback(async () => {
25 const response = await axios.get('/api/user');
26 setUser(user => isEqual(user, response.data) ? user : response.data);
32 React.useEffect(() => {
35 .get('/sanctum/csrf-cookie')
38 timer = setInterval(fetchUser, 5 * 60 * 1000);
41 if (timer) clearInterval(timer);
45 const login = React.useCallback(async (creds) => {
47 await axios.post('/login', {
53 if (error.response && error.response.status === 419) {
54 await axios.get('/sanctum/csrf-cookie');
55 await axios.post('/login', {
66 const logout = React.useCallback(async () => {
67 await axios.post('/logout');
71 return <context.Provider value={{ login, logout, user }}>
76 UserProvider.propTypes = {
77 children: PropTypes.node,