Search code examples
reduxaxiosrtk-query

How to add default options for fetchBaseQuery in RTK Query?


After looking on the Internet for a long time, I have not found whether it is possible to add default options to this library as in axios? Do I have to pass the same options to fetchBaseQuery every time I create an Api?


Solution

  • As you should create only one API in your application in almost all cases, there is really no need for "defaults". The fact that you are creating a fetchBaseQuery is already that default.

    You should only create multiple apis if those are completely independent datasets. So if you had one api that queried against a facebook service and another one that queried against a cake recipe service, that's fine. But it it's the same database and you create one api for authors and one for books, you are not using it as intended.

    This is also mentioned at about 5 different places in the RTK Query docs, for example quoting the Quick Start Tutorial:

    Typically, you should only have one API slice per base URL that your application needs to communicate with. For example, if your site fetches data from both /api/posts and /api/users, you would have a single API slice with /api/ as the base URL, and separate endpoint definitions for posts and users. This allows you to effectively take advantage of automated re-fetching by defining tag relationships across endpoints.

    For maintainability purposes, you may wish to split up endpoint definitions across multiple files, while still maintaining a single API slice which includes all of these endpoints. See code splitting for how you can use the injectEndpoints property to inject API endpoints from other files into a single API slice definition.