question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Option to hydrate createApi using extraReducers

See original GitHub issue

Details

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?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:9
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
phryneascommented, Jun 5, 2021

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.

2reactions
anyxemcommented, Jul 15, 2021

I also need such kind of thing to persist Websocket channel ID to store Example below makes sense if channel ID is determined

const listener = (event) => {
  const data = JSON.parse(event.data)
  if (!isMessage(data) || data.channel !== arg) return

  updateCachedData((draft) => {
    draft.push(data)
  })
}

But it don’t, so I have to store that ID somewhere and then do

if (!isMessage(data) || data.channel !== store.queries['prefix'+arg].websocketChannelId) return
Read more comments on GitHub >

github_iconTop Results From Across the Web

createApi - Redux Toolkit
extractRehydrationInfo ​​​ A function that is passed every dispatched action. If this returns something other than undefined , that return value ...
Read more >
Persistence and Rehydration - Redux Toolkit
Persistence and Rehydration. RTK Query supports rehydration via the extractRehydrationInfo option on createApi .
Read more >
Server Side Rendering - Redux Toolkit
In your createApi call, configure rehydration using the extractRehydrationInfo option: ... import { HYDRATE } from 'next-redux-wrapper'
Read more >
Customizing createApi - Redux Toolkit
You can create your own versions of createApi by either specifying non-default options for the modules or by adding your own modules.
Read more >
Queries - Redux Toolkit
RTK Query > Usage > Queries: fetching data from a server. ... -related options will override the defaults you may have set in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found