1

I have troubles solving common problem, that should be handled by RTKQuery.

When my application starts, it will load configuration. This configuration will contain stuff like baseUrl, some data used in headers etc.

I've used createApi(...) to create configuration slice:

export interface Configuration {
  baseUrl: string;
  language: string;
}

export const configurationApi = createApi({
  reducerPath: "configuration",
  baseQuery: fetchBaseQuery({ baseUrl: "/api" }),
  endpoints: (builder) => ({
    loadConfiguration: builder.query<Configuration, unknown>({ //the generic expects second arugment...
      query: () => "/configuration",
    }),
  }),
});

I want to use the baseUrl and language of the loaded configuration in the following request. The documentation points prepareHeaders as the right place to do it:

export const testApi = createApi({
  reducerPath: "test",
  baseQuery: fetchBaseQuery({
    baseUrl: "/api", //need this from configuration
    prepareHeaders: (headers, { getState }) => {
      const state = getState() as RootState;
     // nees to get language from configuration

I cannot how to access the result from configuration inside the testApi

I cannot find in documentation / examples how to access the data for any endpoint in that matter.

Let's say we have endpoint loadUser :

endpoints: (builder) => ({
    loadUser: builder.query<Partial<UserResponse>, UserRequest>({
      query: ({ userId }) => ({
        url: "/api/user"
      }),
    }),
  }),

Is there easy way to access the latest data ( regarding of the user ID, just latest data for user endpoint ) ? It seems like this should be trivial, but it seems it's not.

Thanks in advance.

Chris Panayotoff
  • 1,744
  • 21
  • 24

1 Answers1

0
const selector = api.endpoints.foo.select(argumentLikeInTheHook)
const result = selector(getState())

You can find the documentation on that here.

But generally keep in mind that if no component is using that endpoint data, it will be cache-collected after (per default) 60 seconds.

phry
  • 35,762
  • 5
  • 67
  • 81
  • It would be helpful to know what exactly `api` is and where it comes from. I'd guess its the second parameter to the `prepareHeaders` function, which is of type `Pick` and thus does not have a field `endpoints` – Alex Feb 06 '22 at 12:11
  • @Alex `api` in that example is the object created by `createApi`. I assumed as this whole question here is about `createApi`, that should be obvious with that naming. – phry Feb 06 '22 at 15:43