'How to show loader during multiple api calls in a loop in React

I have two API's

First API returns list of items which I am iterating to get each item's detailed data.

Here's the code

  const [loader, setLoader] = useState(false);
 
  React.useEffect(() => {
    const fetchUsers = async() => {
      setLoader(true);
      const users = await getUsers();
      const promises = users.map(async (user) => {
          let userData = await getUsersDetailedData(user.userId);
          return userData
      });
      let finalUsers = await Promise.all(promises);
      setLoader(false);
    }
    fetchUsers();
  }, [])

I am updating loader state before the api call and after call but it is not working.

Loader state is updating these many times and loader is not displaying logs



Solution 1:[1]

Try it in this way,

React.useEffect(() => {
  const fetchUsers = async() => {
    const users = await getUsers();
    const promises = users.map(async (user) => {
        let userData = await getUsersDetailedData(user.userId);
        return userData
    });
    let finalUsers = Promise.all(promises);
    return finalUsers;
  }
  setLoader(true);
  fetchUsers().then(res=>{
    setLoader(false);
  });
}, [])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ekhlas Mridha