Redux & Redux Toolkit
/Intermediate
createApi()
Definition
The core function of RTK Query. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data.
Explain Like I'm New
The blueprint for your server communication. You use `createApi` to define your Base URL (e.g., `api.com/v1`), and then list out every single endpoint your app needs (`/users`, `/posts`, `/comments`).
Real World Example
Creating an `apiSlice.js` file using `createApi` that becomes the central hub for all network requests in your application.
Common Use Cases
- •Defining network interfaces
- •Generating React Hooks automatically
Interactive Example
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' // 1. Define the API slice export const pokemonApi = createApi({ reducerPath: 'pokemonApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), // 2. Define the endpoints endpoints: (builder) => ({ getPokemonByName: builder.query({ // This appends to the baseUrl: https://pokeapi.co/api/v2/pokemon/pikachu query: (name) => `pokemon/${name}`, }), }), }) // 3. RTK Query magically generated this hook based on the endpoint name! export const { useGetPokemonByNameQuery } = pokemonApi;
Interview Questions
basic
- What is the recommended number of `createApi` slices a standard application should have?
intermediate
- What property inside `createApi` holds all the specific endpoints you want to fetch?