Currently, there is no way in which the state fetched on the server using createApi can be persisted on the client. People who are building Nextjs or any SSR application might need this functionality so that we can fetch the data on the server and then re-use the same data on the client-side as well.
I had raised a similar issue on the Next Redux Wrapper repository and one solution to handle this would be to provide an option to add extraReducers in the createApi function that RTKQ exposes. Using that, it would be possible to do something like the following:
const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/',
}),
tagTypes: ['Post'],
endpoints: (build) => ({
// All the endpoints
}),
extraReducers(builder) {
builder.addCase(hydrate, (state, action) => {
console.log('HYDRATE', state, action.payload);
return {
...state,
...(action.payload as any)[api. reducerPath],
};
});
},
})
Right now, the only way to persist createApi is to do what @bjoluc suggested:
configureStore({
reducer: {
[slice.name]: slice.reducer,
[api.reducerPath]: (state, action) => action.type !== HYDRATE ? api.reducer(state, action) : {...state, ...(action.payload as unknown)[api.reducerPath]},
},
},
});
Is there any recommended approach to resolving this issue?
Not yet, also this would theoretically need another step of removing any subscriptions coming in from hydration after a while, when all currently rendered components had an option to re-subscribe to relevant data on the client.
Without that step, the re-hydrated data would always be subscribed by the server-side components, which of course will never unmount on the client side.
This is something we will take a look into for the next version of RTK-Query, but not for the first real release.
If you do any experimentation, all insights are very welcome since I don't have a lot of experience with SSR and Next.
I believe swr and react-query both have an initialData option. Would something like that be possible on an endpoint?
Most helpful comment
Not yet, also this would theoretically need another step of removing any subscriptions coming in from hydration after a while, when all currently rendered components had an option to re-subscribe to relevant data on the client.
Without that step, the re-hydrated data would always be subscribed by the server-side components, which of course will never unmount on the client side.
This is something we will take a look into for the next version of RTK-Query, but not for the first real release.
If you do any experimentation, all insights are very welcome since I don't have a lot of experience with SSR and Next.