Redux Toolkit provides the standard Redux utilities for creating a typed data store in a React application. It reduces store setup to two practical steps: define slices for application data, then configure a store that exposes those reducers to components. section 20.5 section 20.6
A typical TypeScript setup uses:
- A slice combining a name, initial state, and reducer functions; createSlice returns the reducer and generated actions. section 20.5
- configureStore to register slice reducers and derive RootState and AppDispatch types for typed React hooks. section 20.5
- RTK Query createApi to describe HTTP endpoints, generate query hooks, and add API reducers and middleware to the store. section 20.5.1
Product selections and remote products
In src/data/selectionSlice.ts, create a selections slice whose initial state is a ProductSelection array and whose addToOrder reducer accepts a product and quantity. In src/data/dataStore.ts, register its reducer and export typed hooks. Components can then select state and dispatch reducers.addToOrder([product, quantity]). A separate storeApis.ts file can expose useGetProductsQuery for products returned by an HTTP service.
Listing 20.22 The contents of the storeApis.ts file in the src/data folder
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { Product } from './entities';
const protocol = "http";
const hostname = "localhost";
const port = 4600;
const baseUrl = `${protocol}://${hostname}:${port}`;
export const productsApi = createApi({
reducerPath: "products",
baseQuery: fetchBaseQuery({baseUrl}),
endpoints: (builder) => ({
getProducts: builder.query<Product[], void>({
query: () => "products"
})
})
})
export const { useGetProductsQuery } = productsApi;
Inspect the complete RTK Query definition, including fetchBaseQuery, the products endpoint, and the generated React hook. section 20.5.1

