I posted a few weeks ago about trying to figure out how to send multiple queries based on an initial query: https://www.reddit.com/r/reactjs/comments/ou1opw/multiple_queries_with_rtk_query/
I had pretty much given up on finding a solution to this and instead was executing individual queries when a corresponding tab was selected. It worked ok, but then there was a delay each time a tab was initially clicked.
Today, while looking at some of the more advanced features of RTK Query, I stumbled on the option to use the queryFn property. This lets you set up some custom logic during the query, and I was able to configure it to take in an array of project IDs, query each of them, and then return a single result set.
Here’s the main chunk of code:
getTickets: builder.query({ queryFn: async (projectIds, _queryApi, _extraOptions, baseQuery) => { const results = await Promise.all(projectIds.map(projectId => baseQuery(`projects/${projectId}/tickets`))); const merged = [].concat(…results.map(result => result.data)); const errors = [].concat(…results.filter(result => result.error != null).map(result => result.error)); if (errors.length > 0) return { error: errors }; return { data: merged }; } })
I think there’s some changes I need to make to get the isLoading (and probably other values) set correctly, but hopefully this can help someone else.
submitted by /u/lucidspoon
[link] [comments]