Skip to content

Commit

Permalink
Add voucher balance subscription (#1415)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikitayutanov authored Sep 27, 2023
1 parent 92409ef commit 402abc3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion utils/gear-hooks/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gear-js/react-hooks",
"version": "0.6.9",
"version": "0.6.10",
"description": "React hooks used across Gear applications",
"author": "Gear Technologies",
"license": "GPL-3.0",
Expand Down
23 changes: 18 additions & 5 deletions utils/gear-hooks/src/hooks/api/voucher/use-voucher-balance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { HexString, generateVoucherId } from '@gear-js/api';
import { UnsubscribePromise } from '@polkadot/api/types';
import { AccountContext, AlertContext, ApiContext } from 'context';
import { useContext, useEffect, useState } from 'react';

Expand All @@ -12,20 +13,32 @@ function useVoucherBalance(programId: HexString | undefined) {
const [voucherBalance, setVoucherBalance] = useState<string>();
const isVoucherBalanceReady = voucherBalance !== undefined;

const voucherId = programId && accountAddress ? generateVoucherId(accountAddress, programId) : undefined;

useEffect(() => {
setVoucherBalance(undefined);

if (!programId || !isApiReady || !accountAddress) return;

const id = generateVoucherId(accountAddress, programId);
if (!isApiReady || !voucherId) return;

api.balance
.findOut(id)
.findOut(voucherId)
.then((result) => setVoucherBalance(result.toString()))
.catch(({ message }: Error) => alert.error(message));

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isApiReady, accountAddress, programId]);
}, [isApiReady, voucherId]);

// TODO: useBalanceSubscription, same as in Account context
useEffect(() => {
if (!isApiReady || !voucherId) return;

const unsub = api.gearEvents.subscribeToBalanceChanges(voucherId, (result) => setVoucherBalance(result.toString()));

return () => {
unsub.then((unsubCallback) => unsubCallback());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isApiReady, voucherId]);

return { voucherBalance, isVoucherBalanceReady };
}
Expand Down

0 comments on commit 402abc3

Please sign in to comment.