Update state within listener that is inside useEffect

7

I have a hook called useQueryEvents that 1) fetches all past transactions for a user and 2) listens to the network for incoming/outgoing transactions. In both cases the transactions are passed into a function addActionToActivity that simply appends it to the activity array and updates it in the context state under the key activity.

I can't get the activity to sync correctly. Whenever the state updates it does not have the last transaction because it's always one step behind. If I add activity to the dependancy it works but then starts a new listener (due to the whole function being called again with the new activity value) which causes an infinity-like-loop which keeps switching up the state.

function useQueryEvents() {
  const { state: { connectedNetwork, selectedWallet, activity },
  } = useContext(LocalContext);

  useEffect(() => {
    async function bootstrapQueryEvents() {
      // First get all the past transactions
      const transactions = await getAllPastTransactions();
      const contract = await getContract();

      // Now save them to context state via addActionToActivity
      await addActionToActivity(transactions, activity);

      // Now that all the past transactions have been saved
      // listen to all incoming/outgoing transactions and
      // save to context state via addActionToActivity
      contract.on('Transfer', async (from, to, amount, event) => {
        console.log(`${from} sent ${ethers.utils.formatEther(amount)} to ${to}`);
        const transaction = await formatEventToTransaction(event);
        await addActionToActivity(transaction, activity);
      });
    }

    bootstrapQueryEvents();
  }, [selectedAsset, connectedNetwork, selectedWallet]); // <- I've tried adding `activity` here
}

Any ideas how I can approach updating the state while having access to the updated activity value inside the listener without starting a new instance of the listener? Or maybe there's a different approach I can take altogether?

Thanks in advance

Share
Improve this question
3
  • Could you please post the code used in addActionToActivity? Just wanted to check how it handles transaction arrays and transactions. Also when you mean it's off by one, does that mean that the contract.on does trigger re-renders? – nipuna777 May 5 at 17:05
  • Without seeing what's in addActionToActivity, we can't really help you. How do you update the state? Do you modify the state directly? – jperl May 12 at 15:54
  • How come none of the dependencies are used in the useEffect? Where is selectedAsset coming from? – jperl May 12 at 16:02

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

Chart JS +ng2-charts not working on Angular+2