ReactJS

    How to Set Up and Use RTK Query in Redux Toolkit


    Introduction

    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.

    Install

    npm install @reduxjs/toolkit react-redux

    Setting up the slice

    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;

    Adding API Reducer to Store

    import { configureStore } from '@reduxjs/toolkit';import { apiSlice } from './apiSlice';export const store = configureStore({reducer: {[apiSlice.reducerPath]: apiSlice.reducer},middleware: (getDefaultMiddleware) =>getDefaultMiddleware().concat(apiSlice.middleware)});

    Fetching Data

    const { data, error, isLoading } = useGetPostsQuery();

    Fetching a single post by ID

    const { data: post } = useGetPostByIdQuery(1);

    Inserting the data

    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.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    ReactJS

    Related Center Of Excellence