'react-query: accessing the query with matching condition (by 1st index of queryKey array)

I've queries like:

useQuery(['myquery',{test:1}], fetchFn)
useQuery(['myquery',{test:2}], fetchFn)
useQuery(['myquery',{test:3}], fetchFn)

I would like to observe the data of all those queries with myquery without knowing the rest of the items of queryKey.

In documentation, as I understood it is possible to observe multiple queries but my matching condition seems not covered.

 const observer = new QueriesObserver(queryClient, [
   { queryKey: ['post', 1], queryFn: fetchPost },
   { queryKey: ['post', 2], queryFn: fetchPost },
 ])
 
 const unsubscribe = observer.subscribe(result => {
   console.log(result)
   unsubscribe()
 })

I could only find similar usage for useIsFetching but it only gives a number of matching queries:

 // How many queries matching the posts prefix are fetching?
 const isFetchingPosts = useIsFetching(['posts'])

But I want to access the result of the queries, specifically the last updated one.



Solution 1:[1]

This is the best thing i can come up with using queryClient :


const Component = () => {
    // match all queries with:
    const keyPrefix = "courseSection_list";

    // since it is loading state, it will trigger twice for each returning result
    const matchingQueriesUpdated = useIsFetching([keyPrefix]);
    const data = useMemo(() => {
        const lastUpdatedMatchingQuery = queryClient.queryCache.queries
            .filter((q) => q.queryKey[0] === keyPrefix) 
            .sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)[0] // sorting puts the last updated one to the 1st index;

        return lastUpdatedMatchingQuery.state.data;
    }, [matchingQueriesUpdated]);

    return <div> bla bla </div>

}

Extra render can be prevented by catching dataUpdatedAt value at 0 for loading state. But i rather keep my code more simple for now.

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