index.jsx 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import { baseUrl } from './baseUrl';
  2. import { h, createContext } from 'preact';
  3. import { MqttProvider } from './mqtt';
  4. import produce from 'immer';
  5. import { useContext, useEffect, useReducer } from 'preact/hooks';
  6. export const FetchStatus = {
  7. NONE: 'none',
  8. LOADING: 'loading',
  9. LOADED: 'loaded',
  10. ERROR: 'error',
  11. };
  12. const initialState = Object.freeze({
  13. host: baseUrl,
  14. queries: {},
  15. });
  16. const Api = createContext(initialState);
  17. function reducer(state, { type, payload, meta }) {
  18. switch (type) {
  19. case 'REQUEST': {
  20. const { url, fetchId } = payload;
  21. const data = state.queries[url]?.data || null;
  22. return produce(state, (draftState) => {
  23. draftState.queries[url] = { status: FetchStatus.LOADING, data, fetchId };
  24. });
  25. }
  26. case 'RESPONSE': {
  27. const { url, ok, data, fetchId } = payload;
  28. return produce(state, (draftState) => {
  29. draftState.queries[url] = { status: ok ? FetchStatus.LOADED : FetchStatus.ERROR, data, fetchId };
  30. });
  31. }
  32. default:
  33. return state;
  34. }
  35. }
  36. export const ApiProvider = ({ children }) => {
  37. const [state, dispatch] = useReducer(reducer, initialState);
  38. return (
  39. <Api.Provider value={{ state, dispatch }}>
  40. <MqttProvider>{children}</MqttProvider>
  41. </Api.Provider>
  42. );
  43. };
  44. function shouldFetch(state, url, fetchId = null) {
  45. if ((fetchId && url in state.queries && state.queries[url].fetchId !== fetchId) || !(url in state.queries)) {
  46. return true;
  47. }
  48. const { status } = state.queries[url];
  49. return status !== FetchStatus.LOADING && status !== FetchStatus.LOADED;
  50. }
  51. export function useFetch(url, fetchId) {
  52. const { state, dispatch } = useContext(Api);
  53. useEffect(() => {
  54. if (!shouldFetch(state, url, fetchId)) {
  55. return;
  56. }
  57. async function fetchData() {
  58. await dispatch({ type: 'REQUEST', payload: { url, fetchId } });
  59. const response = await fetch(`${state.host}${url}`);
  60. try {
  61. const data = await response.json();
  62. await dispatch({ type: 'RESPONSE', payload: { url, ok: response.ok, data, fetchId } });
  63. } catch (e) {
  64. await dispatch({ type: 'RESPONSE', payload: { url, ok: false, data: null, fetchId } });
  65. }
  66. }
  67. fetchData();
  68. }, [url, fetchId, state, dispatch]);
  69. if (!(url in state.queries)) {
  70. return { data: null, status: FetchStatus.NONE };
  71. }
  72. const data = state.queries[url].data || null;
  73. const status = state.queries[url].status;
  74. return { data, status };
  75. }
  76. export function useApiHost() {
  77. const { state } = useContext(Api);
  78. return state.host;
  79. }
  80. export function useEvents(searchParams, fetchId) {
  81. const url = `/api/events${searchParams ? `?${searchParams.toString()}` : ''}`;
  82. return useFetch(url, fetchId);
  83. }
  84. export function useEvent(eventId, fetchId) {
  85. const url = `/api/events/${eventId}`;
  86. return useFetch(url, fetchId);
  87. }
  88. export function useConfig(searchParams, fetchId) {
  89. const url = `/api/config${searchParams ? `?${searchParams.toString()}` : ''}`;
  90. return useFetch(url, fetchId);
  91. }
  92. export function useStats(searchParams, fetchId) {
  93. const url = `/api/stats${searchParams ? `?${searchParams.toString()}` : ''}`;
  94. return useFetch(url, fetchId);
  95. }