Skip to content

Step 4 - Convert Todos component - #8

Open
danieltott wants to merge 22 commits into
03-useLoad-Appfrom
04-todos
Open

Step 4 - Convert Todos component#8
danieltott wants to merge 22 commits into
03-useLoad-Appfrom
04-todos

Conversation

@danieltott

@danieltott danieltott commented May 30, 2019

Copy link
Copy Markdown
Owner

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(user.id, 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;
  reset();
  if (user) {
    load();
    interval = setInterval(() => {
      load();
    }, 6000);
  }

  return () => {
    clearInterval(interval);
  };
}, [load, user, reset]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant