Implementing RTK Query for API Data Fetching
Provide an example of how to use RTK Query with Redux Toolkit 2.0 to fetch data from an API endpoint and store the data in the state.
// Define an API slice using createApi
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://your-api-endpoint.com' }),
endpoints: (builder) => ({
getTodos: builder.query({
query: () => '/todos',
}),
}),
});
// Export the auto-generated hook for the `getTodos` query endpoint
export const { useGetTodosQuery } = apiSlice;
This code snippet defines an API slice with Redux Toolkit 2.0 using createApi. It sets up a base query with fetchBaseQuery to a specified base URL, then creates an endpoint for getting todos. The auto-generated hook useGetTodosQuery is exported for use in React components.
// In your store.js file
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './apiSlice';
export const store = configureStore({
reducer: {
// Add the generated reducer as a specific top-level slice
[apiSlice.reducerPath]: apiSlice.reducer,
},
// Adding the api middleware enables caching, invalidation, polling, and other useful features of RTK Query
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
});
This code snippet sets up the Redux store by including the reducer generated by the apiSlice, and adds the RTK Query middleware to handle caching and other features.
// In a React functional component
import React from 'react';
import { useGetTodosQuery } from './apiSlice';
const Todos = () => {
const { data: todos, error, isLoading } = useGetTodosQuery();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.toString()}</div>;
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};
export default Todos;
In this React component, we use the automatically generated hook from the API slice to fetch and display a list of todos. The hook provides data, error, and isLoading properties to easily handle the API request state in the component.