on 6542dce help sign in
bridge/src/store/pointCache.js
64 lines 1.4 kB history raw
1import React, {
2 createContext,
3 forwardRef,
4 useCallback,
5 useContext,
6 useState,
7} from 'react';
8import * as azimuth from 'azimuth-js';
10import { useNetwork } from './network';
12export const PointCacheContext = createContext(null);
14function _usePointCache() {
15 const { contracts } = useNetwork();
16 const [pointCache, _setPointCache] = useState({});
18 const addToPointCache = useCallback(
19 entry => _setPointCache(cache => ({ ...cache, ...entry })),
20 [_setPointCache]
21 );
23 const fetchPoint = useCallback(
24 async point => {
25 const _contracts = contracts.getOrElse(null);
26 if (!_contracts) {
27 return;
28 }
30 const details = await azimuth.azimuth.getPoint(_contracts, point);
31 addToPointCache({ [point]: details });
32 },
33 [contracts, addToPointCache]
34 );
36 return {
37 pointCache,
38 addToPointCache,
39 fetchPoint,
40 };
43export function PointCacheProvider({ children }) {
44 const pointCache = _usePointCache();
46 return (
47 <PointCacheContext.Provider value={pointCache}>
48 {children}
49 </PointCacheContext.Provider>
50 );
53// Hook version
54export function usePointCache() {
55 return useContext(PointCacheContext);
58// HOC version
59export const withPointCache = Component =>
60 forwardRef((props, ref) => (
61 <PointCacheContext.Consumer>
62 {pointCache => <Component ref={ref} {...pointCache} {...props} />}
63 </PointCacheContext.Consumer>
64 ));