I have a React Native mobile application where I'm trying to manage API requests with RTK Query. On the 'Products' screen, I fetch and display data using getProducts (infinite scroll). On the displayed data, I have a button for deleting the product (deleteProduct). After executing the deleteProduct mutation, I want the deleted product to be removed from the screen. I attempted to use providesTags and invalidatesTags, but since there is a merge part in the query, I couldn't achieve this. Please help me.
export const productApi=baseApi.injectEndpoints({
overrideExisting:true,
endpoints : (builder) => ({
getProducts: builder.query({
query: (page=1) => `url?page=${page}`,
transformResponse: (response) => {
return response.data
},
serializeQueryArgs: ({ endpointName }) => {
return endpointName
},
merge: (currentCache, newItems) => {
currentCache.data.push(...newItems.data)
currentCache.links = newItems?.links;
},
forceRefetch({ currentArg, previousArg }) {
return currentArg !== previousArg
},
providesTags: (result) =>
result
? [
...result.data.map(({ id }) => ({ type: 'Products', id })),
]
: [{ type: 'Products', id: 'PARTIAL-LIST' }],
}),
deleteProduct: builder.mutation({
query : (id) => ({
url: "products/delete",
method: "POST",
body: {
id:id
}
}),
invalidatesTags: (result, error, id) => [
{ type: 'Products', id },
],
})
})
})
You can use
updateQueryDatainsideonQueryStartedto manually update the cache entry for that file Check this out^ Do this instead of
invalidateTagsso you don't trigger a full reloadThe only issue is that your pagination will now be off by one (the next page you load will actually skip one item). So you probably have to add an offset or something to compensate. I'm still trying to figure out myself how to deal with this