Blog>
Snippets

Data Fetching with RTK Query in Redux Toolkit 2.0

Showcase how to use RTK Query's new features within Redux Toolkit 2.0 to efficiently fetch data, cache results, and automatically re-fetch when needed.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const apiSlice = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getPosts: builder.query({
      query: () => 'posts',
      providesTags: ['Post']
    })
  })
});

export const { useGetPostsQuery } = apiSlice;
This code creates a new RTK API slice using createApi. It defines a single endpoint to fetch posts from /api/posts and automatically generates a React hook called useGetPostsQuery for consuming that endpoint. It also defines a tag 'Post' to manage cache invalidation.
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './apiSlice';

export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware)
});
This code sets up the Redux store and adds our apiSlice to the store's reducers. It also adds the apiSlice middleware to the store's middleware chain, which is necessary for the RTK Query lifecycle to function.
import React from 'react';
import { useGetPostsQuery } from './apiSlice';

export default function PostsList() {
  const { data: posts, error, isLoading } = useGetPostsQuery();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.toString()}</div>;

  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}
This React component uses the useGetPostsQuery hook generated by our apiSlice. It handles loading, error, and success states by rendering different UIs accordingly. When posts are fetched successfully, it renders a list of post titles.
body {
  font-family: 'Arial', sans-serif;
}

ul {
  padding-left: 20px;
}

li {
  list-style-type: none;
  margin-bottom: 10px;
  padding: 5px;
  border-radius: 3px;
  background-color: #f0f0f0;
}

li:hover {
  background-color: #e0e0e0;
}
Some basic CSS to style the PostsList component. It sets a global font, styles the list and list items, and adds a hover effect to the list items.