简体   繁体   中英

How to keep updated react context value inside a callback in a custom hook

I have a userContext wrapped my app, I have a custom hook useAnalytics used to send analytics events and I have a Login component which performs the log in and changes the user value in the context and send an event.

My problem is when I do a setUser inside my Login component the updating user data is not reflected in useAnalytics hook which it sends always the user data in every event

Here a sandbox: https://codesandbox.io/s/romantic-perlman-wzxti?file=/src/Login.js You can open the console and see the results after clicking SEND

I know this is probably an anti-pattern but it would be good to know why I get this behavior

Thanks!

The problem is that all set states are async, while the sending of the event is in sync. So you dispatch the change, send the analytic and after a timeout, the state is updated. There are 2 main ways to fix this.

  1. Set a timeout to wait for react to update the state and push the analytic after the state is updated:
setUser({ type: "login", data: { user: "pippo" } });
setTimeout(sendEvent, 16);
  1. Send the analytic with a middleware:

Add a middleware to intercept all reducer changes and push those to the analytic without the hook itself. This will guarantee that you get all changes that you need to track by checking for the action.type and sending the new data from action.payload.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM