Replies: 1 comment
-
|
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
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
TLDR:
Question: When fetching data with RTKQ on the server side, what is the proper way of making sure that redux state does not persist across requests?
Subquestion: If one creates an RTKQ api slice using the
createSlice
api (and then uses theinjectEndpoints
method on that slice), doesn't it make the slice into a singleton that, on the server, persists between requests, along with its state?Another subquestion Can the
resetApiState
be used on the server when a new store is created? If an api slice is a singleton, wouldn't this interrupt any other possible fetches that were started during other requests and that may still be in flight?===========
EXPANDED VERSION OF THE QUESTION
I am using redux-toolkit with RTKQ in a react app with a little bit of server rendering. The app is completely custom-made and does not use any off-the-shelf framework, but perhaps resembles the early Next.js with its pages router. The pages that render on the server export a
serverFetch
function that fetches data with the help of RTKQ.I have recently realized that I am seeing a contamination of redux state between routes. To my utter astonishment, that contamination only appears in some routes and not in others (I can't explain this; I would have thought that if I am leaking state between requests, this would be obvious on any request to any route). This state contamination looks like this in the stringified state sent for rehydration:
A fragment of serialized state sent to the client for rehydration
One obvious lesson that I learnt from this was that I forgot to unsubscribe from a particular query. But it also made it painfully obvious to me that I do not fully understand how redux works on the server.
In particular, here is how I am creating a redux store:
The
restApiSlice
, in turn, is created and exported like this:The above snippet suggests to me that
restApiSlice
becomes a singleton that is created only once during the first module evaluation, and is not recreated at every request to the server. It must be a singleton, because it would be imported in other files that would inject their endpoints into it, like so:Eventually, this
getServerSideReduxStore
function is called in an Express route per every request; so every request creates a brand new store:But, if
restApiSlice
is a singleton, then creating a fresh copy of the store every request won't help, if it uses the samerestApiSlice
every time. And, ifrestApiSlice
holds a state and if it persists through the whole lifetime of a server, how to prevent it from carrying over its state between requests?Beta Was this translation helpful? Give feedback.
All reactions