RTK Query streamlines data fetching and caching in Redux applications, making API management easier with minimal boilerplate. This guide will walk you through setting up RTK Query and utilizing its various parameters effectively.
npm install @reduxjs/toolkit react-redux
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: 'https://jsonplaceholder.typicode.com/'
}),
endpoints: (builder) => ({
getPosts: builder.query({
query: () => 'posts'
}),
getPostById: builder.query({
query: (id) => `posts/${id}`
}),
createPost: builder.mutation({
query: (data) => ({
url: 'posts',
method: 'POST',
body: data
})
})
})
});
export const {
useGetPostsQuery,
useGetPostByIdQuery,
useCreatePostMutation
} = apiSlice;
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './apiSlice';
export const store = configureStore({
reducer: {
[apiSlice.reducerPath]: apiSlice.reducer
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware)
});
const { data, error, isLoading } = useGetPostsQuery();
const { data: post } = useGetPostByIdQuery(1);
const [createPost] = useCreatePostMutation();
createPost({ title: 'New Post', body: 'Post content' });
RTK Query simplifies data fetching, making API integration in Redux seamless. Start using it to handle API calls efficiently!
Ready to transform your business with our technology solutions? Contact us today to Leverage Our Nodejs Expertise.