Code Splitting
RTK Query makes it possible to trim down your initial bundle size by allowing you to inject additional endpoints after you've setup your initial service definition. This can be very beneficial for larger applications that may have many endpoints.
injectEndpoints
accepts a collection of endpoints an one optional parameter of overrideExisting
.
Calling injectEndpoints
will inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. (Unfortunately, it cannot modify the types for the original crossing over files).
So the most basic approach would be to have one empty central api definition:
and then inject the api endpoints in other files and export them from there - that way you will be sure to always import the endpoints in a way that they are definitely injected.
tip
You will get a warning if you inject an endpoint that already exists in development mode when you don't explicitly specify overrideExisting: true
. You will not see this in production and the existing endpoint will just be overriden, so make sure to account for this in your tests.
ApiWithInjectedEndpoints
Typing a "completely injected" API using However, doing this, you will never end up with one "big api definition" that has correct types for all endpoints. Under certain circumstances, that might be useful though. So you can use the ApiWithInjectedEndpoints
to construct this "full api definition" yourself:
Note however, that all endpoints added with ApiWithInjectedEndpoints
are optional on that definition, meaning that you have to check if they are undefined
before using them.
A good strategy using this would be to do a check for undefined
with an asserting function, so you don't have your hooks in a conditional, which would violate the rules of hooks.