import React, { createContext, useContext, useState } from 'react' import { message } from 'antd' import { useHistory } from 'react-router' import { User } from '../types' import { useAppContext } from './AppContext' import { logOut } from '../api' type Props = { children: React.ReactNode } type Context = { user: User | null handleLogin: (name: string, password: string) => void handleLogout: () => void } const UserContext = createContext(null) export const UserContextProvider = ({ children }: Props) => { const api = useAppContext() const history = useHistory() const [user, setUser] = useState(null) const handleLogin = async (username: string, password: string) => { try { const { key } = await api.post( '/dj-rest-auth/login/', { username, password, }, ) if (!key) throw new Error('Problem logging in!') window.localStorage.setItem('cash-stacks-token', key) const user = await api.get(`/dj-rest-auth/user/`) console.log('user', user) if (!user) message.error(`Couldn't find user`) setUser(user) message.success(`logged in as ${user?.name}`, 0.5) } catch (err) { message.error('Login Failed!') } } const handleLogout = async () => { await logOut() setUser(null) message.success('logged out!', 0.5) history.push('/') } return ( {children} ) } export const useUserContext = () => { const context = useContext(UserContext) if (!context) throw new Error( 'UserContext must be called from within the UserContextProvider', ) return context }