mirror of https://github.com/certusone/oyster.git
fix: create and use useLatestState hook to get up to date useState hook state
This commit is contained in:
parent
a332d6a69b
commit
a47b1043b6
|
@ -16,6 +16,7 @@ import {
|
||||||
CloseOutlined,
|
CloseOutlined,
|
||||||
ExclamationCircleOutlined,
|
ExclamationCircleOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
|
import { useLatestState } from '../../hooks/useLatestState';
|
||||||
|
|
||||||
const { useWallet } = contexts.Wallet;
|
const { useWallet } = contexts.Wallet;
|
||||||
const { useConnection } = contexts.Connection;
|
const { useConnection } = contexts.Connection;
|
||||||
|
@ -40,7 +41,7 @@ export function Vote({
|
||||||
|
|
||||||
const userTokenAccount = useAccountByMint(proposal.info.sourceMint);
|
const userTokenAccount = useAccountByMint(proposal.info.sourceMint);
|
||||||
|
|
||||||
const [mode, setMode] = useState(true);
|
const [_, setMode, getLatestMode] = useLatestState(true);
|
||||||
|
|
||||||
const eligibleToView =
|
const eligibleToView =
|
||||||
timelockConfig.info.votingEntryRule == VotingEntryRule.Anytime &&
|
timelockConfig.info.votingEntryRule == VotingEntryRule.Anytime &&
|
||||||
|
@ -76,17 +77,11 @@ export function Vote({
|
||||||
cancelText: LABELS.CANCEL,
|
cancelText: LABELS.CANCEL,
|
||||||
onOk: async () => {
|
onOk: async () => {
|
||||||
if (userTokenAccount) {
|
if (userTokenAccount) {
|
||||||
// mode is out of date in this scope, so we use a trick to get it here.
|
const modeValue = await getLatestMode();
|
||||||
const valueHolder = { mode: true };
|
|
||||||
await setMode(mode => {
|
|
||||||
valueHolder.mode = mode;
|
|
||||||
return mode;
|
|
||||||
});
|
|
||||||
|
|
||||||
const voteAmount = userTokenAccount.info.amount.toNumber();
|
const voteAmount = userTokenAccount.info.amount.toNumber();
|
||||||
|
|
||||||
const yesTokenAmount = valueHolder.mode ? voteAmount : 0;
|
const yesTokenAmount = modeValue ? voteAmount : 0;
|
||||||
const noTokenAmount = !valueHolder.mode ? voteAmount : 0;
|
const noTokenAmount = !modeValue ? voteAmount : 0;
|
||||||
|
|
||||||
await depositSourceTokensAndVote(
|
await depositSourceTokensAndVote(
|
||||||
connection,
|
connection,
|
||||||
|
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
// Extends useState() hook with async getLatestState which can be used in async callbacks where state property would be stale
|
||||||
|
export function useLatestState<T>(initialState: T) {
|
||||||
|
const [state, setState] = useState<T>(initialState);
|
||||||
|
const getLatestState = () =>
|
||||||
|
new Promise<T>(resolve => {
|
||||||
|
setState(s => {
|
||||||
|
resolve(s);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return [state, setState, getLatestState] as const;
|
||||||
|
}
|
Loading…
Reference in New Issue