Description
Imagine the following pattern:
I have hooks such as useFetchTrendingPostsQuery
, useFetchFeaturedPostsQuery
, useFetchTechnologyPostsQuery
, etc... which all return different entities of the same type.
I have a Post
component, which I want to accept only a postId
prop.
There is a useFetchPostQuery
which would accept a postId
param and fetch a single post.
However, I don't want to trigger this query if the post has already been fetched by one of: useFetchTrendingPostsQuery
, useFetchFeaturedPostsQuery
, useFetchTechnologyPostsQuery
.
I can't really use selectFromResult
, because Post
is a generic component and it would have to check all of the different api queries for different types of posts.
I think I could use extraReducers
to put the results from the various query hooks for different types of posts into a single store slice called posts and check that, but that feels like it defats the point of having rtk-query?
One thing I could do is provide tags from the results of those queries, such as:
fetchFeaturedPosts: builder.query({
providesTags: data => {
return data.map(i => ({ type: 'post', id: i.id }));
},
query: fetchFeaturedPostsQuery
}),
fetchTrendingPosts: builder.query({
providesTags: data => {
return data.map(i => ({ type: 'post', id: i.id }));
},
query: fetchTrendingPostsQuery
}),
fetchPost: builder.query({
providesTags: (data, error, arg) => {
return [{ type: 'post', id: arg.postId }];
},
query: fetchPost
}),
I would just need a way to link the {type: 'post', id: postId }
tag back to useFetchPost
in a way that would make it avoid fetching that specific post if the postId matched
.
Essentially, RTK-Query is a document cache by default, but via tags I think user's could have a handy way to manually create normalized relationships between the different queries by processing the data results in providesTags
.