Fetch list items one by one

Viewed 173

I have the following case. I want to get all users and their data on a listing page. The API has the following structure when you call getUsers it just returns an array of ids. Then I need to get each user data by calling getUser query.

What I want is to have something like this, which I know it doesn't work but am wondering how to achieve:

const { data } = useQuery("/api/users", getUsers);
Promise.all(data.map((user) => useQuery("/api/user/" + user.id, getUser)));
1 Answers

Maybe something like this can work?


    const getBatchUser = (userIds) => {
      return Promise.all(userIds.map((id) => getUser(`/api/user/${user.id}`)))
      .then(responses => {
        return Promise.all(
          responses.map(response => {
            return response.json();
          })
        );
      })
      .then(data => data);
    }
    const Component = () => {
      const users = useQuery("/api/users", getUsers);
      const { data, isLoading } = useQuery("batchedQuery", getBatchUser(users.data));
      ...
    }


Related