on 04765bb help sign in
bridge/src/store/lib/useBirthdaysStore.js
52 lines 1.4 kB history raw
1import { useCallback, useState } from 'react';
2import Maybe from 'folktale/maybe';
3import * as azimuth from 'azimuth-js';
5import { useNetwork } from '../network';
7export default function useBirthdayStore() {
8 const { contracts, web3 } = useNetwork();
9 const [birthdayCache, _setBirthdayCache] = useState({});
11 const addToBirthdayCache = useCallback(
12 entry =>
13 _setBirthdayCache(cache => ({
14 ...cache,
15 ...entry,
16 })),
17 [_setBirthdayCache]
18 );
20 const getBirthday = useCallback(
21 point => birthdayCache[point] || Maybe.Nothing(),
22 [birthdayCache]
23 );
25 const syncBirthday = useCallback(
26 async point => {
27 const _contracts = contracts.getOrElse(null);
28 const _web3 = web3.getOrElse(null);
29 if (!_contracts || !web3) {
30 return;
31 }
33 // fetch birthday if not already known—will not change after being set
34 if (Maybe.Nothing.hasInstance(getBirthday(point))) {
35 const birthBlock = await azimuth.azimuth.getActivationBlock(
36 _contracts,
37 point
38 );
40 if (birthBlock > 0) {
41 const block = await _web3.eth.getBlock(birthBlock);
42 addToBirthdayCache({
43 [point]: Maybe.Just(new Date(block.timestamp * 1000)),
44 });
45 }
46 }
47 },
48 [contracts, web3, addToBirthdayCache, getBirthday]
49 );
51 return { getBirthday, syncBirthday };