on master help sign in
bridge/src/store/pointCache.jsx
53 lines 1.5 kB history raw
1import { Nothing } from 'folktale/maybe';
2import React, { createContext, forwardRef, useContext } from 'react';
3import { noop } from 'lodash';
5import useDeepEqualReference from 'lib/useDeepEqualReference';
6import usePointStore from './lib/usePointStore';
8/**
9 * Avoid race condition by setting an initial dummy state. Previously, on
10 * occasion the application would render before the points queries finished
11 * loading data asynchronously from the roller and Infura. This would cause
12 * a crash in Points.tsx when attempting to destructure the data.
13 */
14const initialContext = {
15 details: Nothing(),
16 rekeyDates: Nothing(),
17 controlledPoints: Nothing(),
18 ecliptic: Nothing(),
19 residents: Nothing(),
20 pointCursor: Nothing(),
21 syncDetails: noop,
22 syncEclipticOwner: noop,
23 syncRekeyDate: noop,
24 syncControlledPoints: noop,
25 syncDates: noop,
26 syncResidents: noop,
27 syncExtras: noop,
28};
30export const PointCacheContext = createContext(initialContext);
32export function PointCacheProvider({ children }) {
33 const cache = usePointStore();
35 return (
36 <PointCacheContext.Provider value={useDeepEqualReference(cache)}>
37 {children}
38 </PointCacheContext.Provider>
39 );
42// Hook version
43export function usePointCache() {
44 return useContext(PointCacheContext);
47// HOC version
48export const withPointCache = Component =>
49 forwardRef((props, ref) => (
50 <PointCacheContext.Consumer>
51 {cache => <Component ref={ref} {...cache} {...props} />}
52 </PointCacheContext.Consumer>
53 ));