Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Intermediate

fetchBaseQuery()

Definition

A lightweight wrapper around the native browser `fetch` API provided by RTK Query. It aims to simplify requests by providing sensible defaults like automatically parsing JSON.

Explain Like I'm New

It's RTK Query's built-in version of Axios. Instead of having to manually write `fetch().then(res => res.json())` a hundred times, `fetchBaseQuery` handles the JSON parsing and error throwing for you.

Real World Example

Using `fetchBaseQuery` to automatically attach a Bearer Token (JWT) to the `Authorization` header of every single outgoing API request.

Common Use Cases

  • •Setting base URLs
  • •Injecting authorization headers globally

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Does `fetchBaseQuery` automatically convert JSON responses into JavaScript objects?

intermediate

  • How do you attach a JWT token from your Redux store to every request using `fetchBaseQuery`?

Flash Cards

Question

Auto convert JSON?

Click to reveal answer
Answer

Yes! Just like Axios, it parses the JSON automatically so you don't have to.

Question

Attach JWT?

Click to reveal answer
Answer

You use the `prepareHeaders` callback. You can call `getState()` inside of it to grab the token from your Redux Auth slice, and append it to the headers.