How to access rtk-query slice data for given endpoint / from prepareHeaders?

Viewed 1167

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.

1 Answers
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.

Related