import { h, createContext } from 'preact'; import { useEffect, useContext } from 'preact/hooks'; import { useDispatcher, fetchJSON } from './actions'; const initialState = { user: null, discussions: [] }; const reducer = (action) => { switch (action.type) { case 'login': { const { username, password } = action; return fetchJSON('/discdag/login', 'POST', { username, password }) .then(() => reducer({ type: 'refresh' })); } case 'logout': { return fetchJSON('/discdag/logout', 'POST') .then(() => reducer({ type: 'refresh' })); } case 'refresh': { return fetchJSON('/discdag/list') .then(({ user, discussions }) => (state) => ({ ...state, user, discussions }) ); } default: return undefined; } }; const UserContext = createContext(initialState); export const UserContainer = ({ children }) => { const { state, dispatch, DispatchProvider } = useDispatcher({ reducer, initialState, }); useEffect(() => dispatch({ type: 'refresh' }), []); return ( {children} ); }; export const useUser = () => useContext(UserContext);