0

Overview

The below functional component renders the list of users in a dropdown. In the edit mode, we can change the current user to another user from the list of users.

Expected

The given code is fetching details thrice. I need to reduce it to one.

function UsersListView(props){
const { edit } = props // this is true for this case.
const refreshUsers = useRef(true);
const [error,users,refersh]=useFetchData('/profiles')
 
useEffect(() => {
  if(edit && refreshUsers.current){
   const fetchData = async () => {
     await refresh();
   }
  fetchData();
  refreshUsers.current = false;
 }
},[edit, refresh])


return ( 
 ...... JSX CODE TO RENDER USERS
 )

}

In the above code, we are making 3 API calls.

  1. In the initial render
  2. When we refresh the data => We fetch the data again. => API called
  3. As refresh is in the dependency of useEffect() hook a re-render occurs then calling useFetchData() => API called.

My attempt

Initially refershUsers.current=false is under await refresh() which got me 8 API calls. The above-mentioned code still gives me 3 API calls.

I tried moving const [error,users,refersh]=useFetchData('/profiles') inside useEffect() which throws an error. Hooks can't be used inside callbacks.

Queries

  1. Is there a way to reduce the API calls to 1.
  2. Why were the API calls reduced from 8 to 3 when I moved the line refershUsers.current=false outside

1 Answer 1

1

Try using a separate useEffect for each dependency. React allows you to use multiple useEffect within the same component.

one of them could be with an empty dependency array for the initial fetch. and then update state or make additional fetch calls as needed in another useEffect

Sign up to request clarification or add additional context in comments.

1 Comment

Tried this before. I separated refreshUsers.current = false into a new useEffect hook with empty array. We can't pass useEffect with empty dependency for fetch part as we have edit and refresh inside it we need to pass them in the dependency array else we get an eslint warning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.