This content originally appeared on DEV Community and was authored by Kauna Hassan
Introduction
Fetching data from an API can be a tedious and time-consuming task, but with the right tools and techniques, it can be made easier and more efficient. One such tool is Redux Toolkit Query (RTK Query), which is a powerful library that simplifies data fetching and caching for Redux applications.
In this article, we will explore how to use RTK Query to fetch data from an API and how it can make your life easier. We will also provide code samples to help you get started.
Getting Started
Before we dive into the code, it's important to understand what RTK Query is and how it works. RTK Query is a library that provides a set of hooks and utilities to help you fetch data from APIs and manage their state in your Redux store.
One of the key features of RTK Query is its caching mechanism. It automatically caches the responses from your API requests, which helps to reduce the number of requests made and improve the performance of your application.
Another important feature of RTK Query is its ability to handle complex API responses. It can handle nested data structures and can normalise the response data into a normalised data structure that is easier to work with.
Now that we have a basic understanding of RTK Query, let's see how we can use it to fetch data from an API.
Fetching Data
Create a new React app using Create React App:
npx create-react-app my-app
cd my-app
Install the required dependencies:
npm install @reduxjs/toolkit react-redux @reduxjs/toolkit/query axios
@reduxjs/toolkitprovides the necessary tools for creating the Redux store and slices.react-reduxprovides the necessary components for integrating Redux with React.@reduxjs/toolkit/queryprovides the necessary tools for using RTK Query.axiosis a popular library for making HTTP requests.
Create a new RTK Query API slice:
Create a new file called api.js in the src directory with the following content:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
import axios from 'axios';
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: 'https://jsonplaceholder.typicode.com/',
}),
endpoints: (builder) => ({
getPosts: builder.query({
query: () => 'posts',
}),
}),
tagTypes: ['Post'],
endpoints: (builder) => ({
getPost: builder.query({
query: (id) => `posts/${id}`,
transformResponse: (response) => ({
...response,
tag: 'Post',
}),
providesTags: (result, error, id) => [{ type: 'Post', id }],
}),
}),
});
export const { useGetPostsQuery, useGetPostQuery } = apiSlice;
The
createApifunction creates a new RTK Query API slice.
reducerPath specifies the name of the Redux store slice for the API.baseQueryspecifies the function for making HTTP requests to the API.endpointsspecifies the API endpoints that can be used by RTK Query.tagTypesspecifies the different types of tags that can be used to cache API responses.transformResponsespecifies a function to transform the API response before it is stored in the cache.providesTagsspecifies the tags that should be used to cache the API response.
Create a new Redux store:
Create a new file called store.js in the src directory with the following content:
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './api';
export const store = configureStore({
reducer: {
[apiSlice.reducerPath]: apiSlice.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
});
configureStorecreates a new Redux store.The
reducerproperty specifies the reducers used by the store.The
middlewareproperty specifies the middleware used by the store.
Use the RTK Query hooks in your React components:
Create a new file called App.js in the src directory with the following content:
import { useGetPostsQuery, useGetPostQuery } from './api';
function App() {
const { data: posts, isLoading: isLoadingPosts, error: errorPosts } =
useGetPostsQuery();
const { data: post, isLoading: isLoadingPost, error: errorPost } =
useGetPostQuery(1);
return (
<div>
<h1>Posts</h1>
{isLoadingPosts && <p>Loading posts...</p>}
{errorPosts && <p>Error loading posts: {errorPosts}</p>}
{posts &&
posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
<h1>Post 1</h1>
{isLoadingPost && <p>Loading post...</p>}
{errorPost && <p>Error loading post: {errorPost}</p>}
{post && (
<div>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
)}
</div>
);
}
export default App;
- The
useGetPostsQueryhook is used to fetch all the posts from the API. - The
useGetPostQueryhook is used to fetch a specific post from the API. - The
dataproperty contains the data returned by the API. - The
isLoadingproperty indicates whether the API is currently loading. - The
errorproperty contains the error returned by the API.
Run the React app:
npm start
Conclusion
In conclusion, RTK Query is a powerful library that simplifies data fetching and caching for Redux applications. It provides a set of hooks and utilities that make it easy to fetch data from APIs and manage their state in your Redux store.
This content originally appeared on DEV Community and was authored by Kauna Hassan
Kauna Hassan | Sciencx (2023-04-20T10:15:59+00:00) Fetching Data Made Easy with RTK Query: A Comprehensive Guide. Retrieved from https://www.scien.cx/2023/04/20/fetching-data-made-easy-with-rtk-query-a-comprehensive-guide/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.