Next.js Discord

Discord Forum

App Router + RTK Query + SSR = No Cache Invalidation

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Avatar
Giant pandaOP
I'm trying to get RTK Query to allow for caching and invalidation on both server and client. Caching and invalidation seem to work properly on the client, but the cache never invalidates on the server, even after a rebuild. Tagging is set up in a pretty standard way within the createApi definition. I am also manually invalidating the cache within my backend api routes when necessary. I also tried using the forceRefetch option within initiate, but makes no difference.

tagTypes in createApi:

tagTypes: ['Products'],


Endpoint Definition:

getProductById: build.query<GetProductApiResponseDto, string>({
query: (id) => ${baseUrl}/${id},
providesTags: (result) => [{ type: 'Products', id: result?._id }],
}),
editProduct: build.mutation<MyProductDto, EditForm>({
queryFn: async (arg, baseQueryApi, extraOptions, baseQuery) => {
...
},
invalidatesTags: (result) => [
{ type: 'Products', id: result?.updatedId },
'Products',
],
}),


The Store:

export const myStore = configureStore({
reducer: {
[myApi.reducerPath]: myApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(myApi.middleware),
});

setupListeners(myStore.dispatch);

export type RootState = ReturnType<typeof myStore.getState>;
export type AppDispatch = typeof myStore.dispatch;


Invalidation Code in app/api/products/route.ts:

myApi.util.invalidateTags(['Products']);


Data Fetching in Server Page:

const store = myStore;
const result = await store.dispatch(
getProductById.initiate(params.id, { forceRefetch: true })
);
// !!This is always old data after editing, checked against the data in the database.
const product = result.data;

0 Replies