乐闻世界logo
搜索文章和话题

How to get response for a certain query in useQueries

1个答案

1

In the React Query library, useQueries is a powerful hook that allows you to run multiple asynchronous queries concurrently and track their states. This hook is very useful when you need to fetch multiple data sources simultaneously based on user input or related data points.

How to Retrieve Responses for Specific Queries with useQueries

To use useQueries to retrieve responses for specific queries, you first need to construct a query array where each query includes a unique queryKey and a queryFn function. Each query returns its state and data, so you can access the response for a specific query via indexing or other methods.

javascript
import { useQueries } from 'react-query'; function fetchUserData(userId) { return fetch(`https://api.example.com/users/${userId}`) .then(res => res.json()); } function fetchProjects(userId) { return fetch(`https://api.example.com/users/${userId}/projects`) .then(res => res.json()); } function MyComponent({ userId }) { const results = useQueries([ { queryKey: ['user', userId], queryFn: () => fetchUserData(userId) }, { queryKey: ['projects', userId], queryFn: () => fetchProjects(userId) } ]); const userData = results[0].data; const projectsData = results[1].data; if (results.some(result => result.isLoading)) { return <div>Loading...</div>; } if (results.some(result => result.isError)) { return <div>Error occurred!</div>; } return ( <div> <h1>{userData.name}</h1> <ul> {projectsData.map(project => ( <li key={project.id}>{project.name}</li> ))} </ul> </div> ); }

Explanation

In the code example above:

  1. We use the useQueries hook to initiate two API requests concurrently: one for user data and another for the user's project list.

  2. Each query is defined by an object including queryKey and queryFn. queryKey is an array used to uniquely identify the query; queryFn is a function that returns a promise resolving to the data.

  3. useQueries returns an array results, where each element corresponds to the result of a query in the input array.

  4. We access the results via indexing to get user data and project data.

  5. In the rendering section, we first check if any query is loading or has an error, then display the user name and project list.

This approach offers the advantage of handling multiple concurrent data requests in a structured and responsive manner while maintaining code readability and maintainability.

2024年8月5日 11:17 回复

你的答案