1

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.

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Yes - that was also what i ended up with
Is it possible to have this wait on the previous call to finish before starting a new one? Lets say I have an array of 5 calls all the same endpoint but with a different ID, user/id/1, user/id/2 and so on.

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.