aboutsummaryrefslogtreecommitdiffstats
path: root/client/src/user.js
blob: dfa6384b90856a51f2cd4764a8db7e2046a6fd52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { h, createContext } from 'preact';
import { useRef, useState, useCallback, useEffect, useContext } from 'preact/hooks';
import { API_PREFIX } from './config';

const fetchJSON = async (url, method='GET', data=undefined) => {
  const res = await fetch(API_PREFIX + url, {
    method,
    credentials: 'include',
    headers: { 'content-type': data && 'application/json' },
    body: data && JSON.stringify(data),
  });

  if (res.status !== 200)
    throw new Error("wrong status");

  return res.json();
};

const initialState = { user: null, discussions: [] };
const reducer = async (action, ref) => {
  switch (action.type) {
    case 'login': {
      const { username, password } = action;
      await fetchJSON('/discdag/login', 'POST', { username, password });
      return await reducer({ type: 'refresh' }, ref);
    }

    case 'logout': {
      await fetchJSON('/discdag/logout', 'POST');
      return await reducer({ type: 'refresh' }, ref);
    }

    case 'refresh': {
      const { user, discussions } = await fetchJSON('/discdag/list');
      return { ...ref.current, user, discussions };
    }

    default:
      throw new Error('Unexpected action');
  }
};

const UserContext = createContext({
  state: initialState,
  dispatch: () => {
    throw new Error("no UserContext Provider!");
  },
});

export const UserContainer = ({ children }) => {
  const ref = useRef();
  const [state, setState] = useState(initialState);
  ref.current = state;

  const dispatch = useCallback(async (action) => {
    const nextState = await reducer(action, ref);
    setState(nextState);
  }, [ref]);

  useEffect(() => dispatch({ type: 'refresh' }), []);

  return (
    <UserContext.Provider value={{ state, dispatch }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => useContext(UserContext).state;
export const useDispatch = () => useContext(UserContext).dispatch;
export const useUserCtx = () => useContext(UserContext);