on adbcda8 help sign in
bridge/src/store/lib/useInvitesStore.js
76 lines 2.0 kB history raw
1import { useCallback, useState } from 'react';
2import Maybe from 'folktale/maybe';
3import * as azimuth from 'azimuth-js';
5import { useNetwork } from '../network';
7// the default value of a point's invites
8const kEmptyInvites = {
9 availableInvites: Maybe.Nothing(),
10 sentInvites: Maybe.Nothing(),
11 acceptedInvites: Maybe.Nothing(),
12};
14export default function useInvitesStore() {
15 const { contracts } = useNetwork();
16 const [invitesCache, _setInvitesCache] = useState({});
18 const addToInvitesCache = useCallback(
19 entry =>
20 _setInvitesCache(cache => ({
21 ...cache,
22 ...entry,
23 })),
24 [_setInvitesCache]
25 );
27 const getInvites = useCallback(
28 point => invitesCache[point] || kEmptyInvites,
29 [invitesCache]
30 );
32 const syncInvites = useCallback(
33 async point => {
34 const _contracts = contracts.getOrElse(null);
35 if (!_contracts) {
36 return;
37 }
39 const availableInvites = await azimuth.delegatedSending.getTotalUsableInvites(
40 _contracts,
41 point
42 );
44 const invitedPoints = await azimuth.delegatedSending.getInvited(
45 _contracts,
46 point
47 );
48 const invitedPointDetails = await Promise.all(
49 invitedPoints.map(async invitedPoint => {
50 console.log('invitedPoint', invitedPoint, typeof invitedPoint);
51 const active = await azimuth.azimuth.isActive(
52 _contracts,
53 invitedPoint
54 );
55 return {
56 point: Number(invitedPoint),
57 active,
58 };
59 })
60 );
61 const sentInvites = invitedPointDetails.length;
62 const acceptedInvites = invitedPointDetails.filter(i => i.active).length;
64 addToInvitesCache({
65 [point]: {
66 availableInvites: Maybe.Just(availableInvites),
67 sentInvites: Maybe.Just(sentInvites),
68 acceptedInvites: Maybe.Just(acceptedInvites),
69 },
70 });
71 },
72 [contracts, addToInvitesCache]
73 );
75 return { getInvites, syncInvites };