RTK query with invalidate tags #4433
AvivaWang8819
started this conversation in
General
Replies: 1 comment
-
Show your current implementation. It should be something like this export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/fakeApi' }),
tagTypes: ['Post'],
endpoints: builder => ({
// omit other endpoints
addReaction: builder.mutation({
query: ({ postId, reaction }) => ({
url: `posts/${postId}/reactions`,
method: 'POST',
// In a real app, we'd probably need to base this on user ID somehow
// so that a user can't do the same reaction more than once
body: { reaction }
}),
async onQueryStarted({ postId, reaction }, { dispatch, queryFulfilled }) {
// `updateQueryData` requires the endpoint name and cache key arguments,
// so it knows which piece of cache state to update
const patchResult = dispatch(
apiSlice.util.updateQueryData('getPosts', undefined, draft => {
// The `draft` is Immer-wrapped and can be "mutated" like in createSlice
const post = draft.find(post => post.id === postId)
if (post) {
post.reactions[reaction]++
}
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()
}
}
})
})
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have two requests, getReports and updateShareUser. getReports is used to obtain list information, updateShareUser is used to update information of a piece of data. When executing updateShareUser, I hope to update the data of getReports using optimistic update, but at the same time I want to invalidate the catch request of getReports in order to next time getReports can send request to the server. The problem is that I do not want to fetch getReports immediately after I update the getReports catch, I just want the browser to send the request when requesting getReports.
I want to when I optimistic update the getReports data don't send request to the server, but when I next time click a button to request getReports API, send this API the server not from catch data.
I'm looking for a way to achieve optimistic updates for your getReports data without triggering an immediate refetch of the data from the server, but still ensuring that subsequent requests for getReports fetch the data from the server instead of the cache.
Beta Was this translation helpful? Give feedback.
All reactions