Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Step 4 - Convert Todos component #8

wants to merge 22 commits into
base: 03-useLoad-App


None yet
1 participant
Copy link

commented May 30, 2019

To integrate useLoad into <Todos>, we needed to add some features to useLoad. A reset function allows us to reset the state back to its initial state. We also needed a way to prevent out-of-order dispatches - if you switched the user prop while the fetch was still loading, you would see a flash of the initial user's data and then the correct data.

To prevent this, we can use useRef, which gives us a mutable variable that we can leverage to keep track of whether we should throw away an update. The useRef value persists across renders, and will always have the current value regardless of which render is being run. It is very similar to a class property. Since our load function creates a closure, we can set a local variable to the useRef current value, and then compare them after running our async function.

The integration into <Todos> is similar to the integration into <App>. One difference here is that since our API function uses props as parameters (Api.fetchTodosByUser(, showCompleted)), we need to wrap it in useCallback so that it isn't being re-created every render.

To get management of our interval that calls load every few seconds, we can make a pretty simple useEffect:

useEffect(() => {
  let interval;
  if (user) {
    interval = setInterval(() => {
    }, 6000);

  return () => {
}, [load, user, reset]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.