'React query used multiple times in same component
I have a component that contains a select (drop down) with multiselect, and each time a new item is selected i want to fetch data related to the value using react query and append this data to my state model of all selected values. However, currently i can't see how this is done using react query, as my useQuery
needs to be created with the id to fetch defined already.
In short - how can i keep fetching object defined by an key using react query on the same component.
Solution 1:[1]
This sounds like a good use-case for the useQueries hook. Given your selection that is likely an Array of some sort, you can map over that and fire off multiple requests. Then, you'll get a result array with all the responses of all the selected elements, which you can append wherever you need to:
const [selection, setSelection] = React.useState([])
const results = useQueries(
selection.map(item => ({
queryKey: ['something', item]
queryFn: () => fetchItem(item)
})
)
const data = results.map(result => result.data)
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 | TkDodo |