Redux Toolkit RTK fetchBasedQuery.prepareHeaders not working on the first call

2.9k Views Asked by At

I have this apiSlice:

export const apiSlice = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: `${baseUrl}${apiBasePath}`,
    prepareHeaders: prepHeaders,
  }),
  endpoints: (builder) => ({
    getPersonById: builder.query({
      query: (personId) => ({
        url: `person/${personId}`,
      }),
    }),
  }),
});

const prepHeaders = (headers, { getState }) => {
  const { token } = getState().auth;
  headers.set('X-Request-Id', uuidv4());
  headers.set('X-Client-Id', 'xxx');
  headers.set('X-Client-Version', '1.0.0');
  headers.set('Content-Type', 'application/vnd.api+json');
  headers.set('Accept', 'application/vnd.api+json');
  headers.set('Authorization', `Bearer ${token}`);
  return headers;
};

Which is being used in this component:

const PersonDetails = () => {
  const { personId } = useParams();

  const { data, error, isLoading, isFetching } =
    useGetPersonByIdQuery(personId);
  return (<div>...render logic removed...</div>)
}

On load of the ReactJS page, it triggers the apiSlice right away since the default landing page renders the PersonDetails component.

1.But the first call has missing headers:

enter image description here

2.Refetching it via the refetch function now contains the headers: enter image description here

UPDATE #1: Just observed that the Unit Test works fine and has the headers; so its really just when the App is actually running in the browser when this weird behaviour is occurring, what could it be?

UPDATE #2: Looks like it might be related to MirageJS when its turned on to as to intercept calls and return mock data. I observed that if I turn it off on startup, the initial call to the actual API has the headers. So I guess the question is now why is MirageJS causing this issue?

0

There are 0 best solutions below