RTK Query: can I fetch all posts initially, refetch only one post? #1479
Replies: 2 comments
-
Looks like this question is asking something very similar. |
Beta Was this translation helpful? Give feedback.
-
There is no inbuilt support for this currently. Besides potentially having See cache-behavior#no-normalized-or-de-duplicated-cache for some more information on this decision. Note that RTK Query attempts to maintain references to the unchanged data for a single query. I.e. for your In terms of options for your situation, if invalidating the entire list isn't suitable for whatever reason, you can:
e.g. // self-defined hook to pick out the todo from the list query
const useGetTodoById = (id: number) => {
return = useGetTodosQuery(undefined, {
selectFromResult: (result) => ({
todo: result.data?.find((todo) => todo.id === id),
...result // note: include just the pieces of `result` you care about rather than spreading all of it in order to render-optimize this hook
})
});
} and to update it in the cache manually after your mutation: editPost: builder.mutation({
query: (id) => ({
url: `/edit`,
method: 'POST',
body: {post_id: id},
}),
transformResponse: (response: any) => {
return response.data;
},
// explicitly *don't* invalidate tags for the `Post`, since we're updating the cache manually
async onQueryStarted(id, { dispatch, queryFulfilled }) {
try {
const { data: updatedPost } = await queryFulfilled
const patchResult = dispatch(
api.util.updateQueryData('getPosts', undefined, (draft) => {
// find and update the corresponding post in the cache if it exists
const draftPost = draft.find((_draftPost) => _draftPost.id === updatedPost.id);
if (!draftPost) return;
Object.assign(draftPost, updatedPost);
})
)
} catch {}
},
}), |
Beta Was this translation helpful? Give feedback.
-
I'm building an app that's very close to the tutorial and I've been stuck on a simple thing for a few days. Just like the tutorial, I have endpoints for
getPosts
(all) andgetPost
(one).I want to:
getPosts
So far, I've only been able to get these two scenarios:
getPost
, which causes the post to be invalidated and refetched after it's edited. The problem is that I have numerous requests to fetch the initial posts. (GET post1
,GET post2
, etc...)Relevant code:
Beta Was this translation helpful? Give feedback.
All reactions