-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
There's a few related open issues that that are variations on this, so writing this up officially.
Problem Statement
RTK Query's createApi currently exists in two forms: there's the UI-agnostic form in @reduxjs/toolkit/query that only generates thunks for each endpoint, and the React-enhanced version in @reduxjs/toolkit/query/react that also builds in all of the hook generation capabilities.
However, these are incompatible with each other. More specifically, if you call the core createApi() and also call the React createApi() these create similar API slice objects, but there's no way to take an existing core API slice object and extend it with the additional React capabilities.
This is a problem in a couple ways. The biggest is that you may want to use RTKQ on the server (such as in a Server Component / SSR environment), so it would be reasonable to import your RTKQ API slice object and dispatch the thunks on the server... but those environments don't like hook imports and throw on import. So, you have to create a core/non-React API slice, which is duplicated effort and imports.
In general, it's a reasonable architectural idea to say "I have a core RTKQ API slice created, I would like to extend or copy it to add the hooks functionality too".
Architecture
At the technical level, the React hooks generation is done via calling buildCreateApi() with the additional "React Hooks Module". This has an init() method that calls buildHooks() internally, then exposes a {injectEndpoint() } object. buildCreateApi() then does const initializedModules = modules.map(m => m.init(ctx)), and then later for (const m of modules) { m.injectEndpoint() }.
Conceptually, it feels like we ought to be able to make this into a separated step process somehow. I don't know what that would look like architecturally, or type-wise.
Ben tried to play with this briefly in #4128 , but I haven't looked at it.
This is almost definitely a "3.0"-level project because it would require significant changes to the public API.
Also potentially has impacts around SSR and RSC use cases somehow.
Semi-related issues:
- Create react hook from base api #4964
- [RED-15] Sharing a set of endpoints between the two
Apis? #3598 - Re-use Api Endpoints & Extend RTK Query Base Queries #3674
Early experiment PR: