Search code examples
reactjsethereumsoliditymetamask

React how to run 2 function async simultaneously using metamask?


I woudlike to run 2 pending in my metamask wallet : stake then harvest :

const [pendingTx, setPendingTx] = useState(false)
const {onReward} = useHarvest(pid)
const {onStake} = useStake(3)

<Button
                        disabled={rawEarningsBalance === 0 || pendingTx}
                        size='sm'
                        variant='secondary'
                        marginBottom='15px'
                        onClick={async () => {
                            setPendingTx(true)
                            await onStake(rawEarningsBalance.toString())
                            await onReward()
                            setPendingTx(false)
                        }
                        }
                    >
                        {TranslateString(999, 'Pack it')}
                    </Button>

Actually when I run it my first function run (await onStake) but after my wallet metamask don't show me to confirm harvest. It show me unauthorized so I need to click on it to show the pending popup


Solution

  • I don't know if I got your problem... If you want to run onStake in parallel with onReward you can not use await in front of each because then it waits for this specific promise to complete. You can instead add all your promises which should run in parallel to a Promise.all and await on this multi-promise object.

    onClick={async () => {
        setPendingTx(true)
        await Promise.all([
            onStake(rawEarningsBalance.toString()),
            onReward()
        ]);
        setPendingTx(false)
    }