Redux Toolkit
Tags: react, reactredux, reduxtoolkit, javascript
Published: 2022-10-18 05:34:47

**Folder Structure**

![Folder Photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4fry5uoycjjpa4zzj8p.png)

**Index.js**

```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

import { Provider } from 'react-redux'
import { store } from './app/Store'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>,
  </React.StrictMode>
);

```
**App.js**

```javascript
import './App.css';
import { useGetAllPostQuery, useGetPostByIdQuery, useGetPostByLimitQuery, useDeletePostMutation, useCreatePostMutation, useUpdatePostMutation } from "./services/Post"

// useGetAllPostQuery
// function App() {
//   const responseInfo = useGetAllPostQuery();
//   console.log('aksh', responseInfo);
//   if (responseInfo.isLoading) {
//     return <h1>Loading ....</h1>
//   }
//   else {
//     if (responseInfo.status === "fulfilled") {
//       return (
//         <div className="App">
//           <h1> AKSH </h1>
//           {responseInfo.data.map((item, index) => {
//             return <div key={item._id}>{index + 1}. {item.title} - {item.desc} </div>
//           })}
//         </div>
//       );
//     }
//     else {
//       return <h1> Something went wrong</h1>
//     }
//   }
//   // return (
//   //   <div className="App">
//   //     <h1>Hello World</h1>
//   //     {responseInfo.isLoading ? "loading": "success"}
//   //   </div>
//   // );
// }


// useGetPostByIdQuery
function App() {
  const response = useGetPostByIdQuery("63027141185460b394772d38");
  console.log(response)
  return (
    <h1> Hi </h1>
  )
}


// GetPostByLimitQuery
function App() {
  const { data, error, isLoading } = useGetPostByLimitQuery(2);
  return (
    <>
      {error ? (
        <>Oh no, there was an error</>
      ) : isLoading ? (
        <>Loading...</>
      ) : data ? (
        <>
          <h3>
            {
              data.map((item, index) => {
                return <div key={item._id}>{item.title}</div>
              })
            }
          </h3>
        </>
      ) : <h1>meow</h1>}
    </>
  )
}

// useDeletePostMutation
function App() {
  const [deletePost, responseInfo] = useDeletePostMutation();
  console.log(responseInfo);
  return (
    <div className="App">

      <button onClick={() => { deletePost("63027141185460b394772d38") }}>Delete Post</button>
    </div>
  )
}

// useCreatePostMutation 
function App() {
  const [createpost, responseInfo] = useCreatePostMutation();
  console.log(responseInfo);
  return (
    <>
      <h2>Redux Toolkit - RTK Query(Create Data)</h2>
      {responseInfo.status === "uninitialized" ? ("Click the Button") : (responseInfo.status === "pending" ? ("Loading") : ("Success"))}
      <button onClick={() => {
        createpost({
          title: "4",
          desc: "4"
        })
      }}>Click</button>
    </>
  )
}

// useUpdatePostMutation
function App() {
  const [updatePost, responseInfo] = useUpdatePostMutation();
  console.log(responseInfo);
  return (
    <>
      <h1>Create Data</h1>
      <button onClick={() => {
        updatePost({
          id1: "63027148185460b394772d3a",
          title: "meo1"
        })
      }}>Click</button>
    </>
  )
}
export default App;

```
**post.js**

```javascript
// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

// Define a service using a base URL and expected endpoints
export const postApi = createApi({
    reducerPath: 'postApi1',
    baseQuery: fetchBaseQuery({ baseUrl: 'http://127.0.0.1:8000/' }),

    endpoints: (builder) => ({
        getAllPost: builder.query({
            query: () => ({
                url: 'student',
                method: 'GET'
            }),
        }),

        // getPostById: builder.query({
        //     query: (id) => ({
        //         url: `student/${id}`,
        //         method: 'GET'
        //     })
        // }),

        getPostById: builder.query({
            query: (id) => {
                console.log(id);
                return {
                    url: `student/${id}`,
                    method: 'GET'
                }
            }
        }),

        getPostByLimit: builder.query({
            query: (num) => {
                console.log("Limit Number", num);
                return {
                    url: `student?_limit=${num}`,
                    method: 'GET'
                }
            }
        }),

        deletePost: builder.mutation({
            query: (id) => {
                console.log("Delete id", id);
                return {
                    url: `student/${id}`,
                    method: 'DELETE'
                }
            }
        }),

        createPost: builder.mutation({
            query: (newPost) => {
                console.log('create post', newPost);
                return {
                    url: 'student',
                    method: 'POST',
                    body: newPost,
                    headers: {
                        'Content-type': 'application/json; charset=UTF-8',
                    }
                }
            }
        }),

        updatePost: builder.mutation({
            query: (updatePostData) => {
                console.log('update post', updatePostData);
                return {
                    url: `student/${updatePostData.id1}`,
                    method: 'PUT',
                    body: updatePostData,
                    headers: {
                        'Content-type': 'application/json; charset=UTF-8',
                    }
                }
            }
        })
    }),
})

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetAllPostQuery, useGetPostByIdQuery, useGetPostByLimitQuery, useDeletePostMutation, useCreatePostMutation, useUpdatePostMutation } = postApi;
```
**store.js**

```javascript
import { configureStore } from '@reduxjs/toolkit'
// Or from '@reduxjs/toolkit/query/react'
import { setupListeners } from '@reduxjs/toolkit/query'
import { postApi } from '../services/Post'

export const store = configureStore({
    reducer: {
        // Add the generated reducer as a specific top-level slice
        [postApi.reducerPath]: postApi.reducer,
    },
    // Adding the api middleware enables caching, invalidation, polling,
    // and other useful features of `rtk-query`.
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(postApi.middleware),
})

// optional, but required for refetchOnFocus/refetchOnReconnect behaviors
// see `setupListeners` docs - takes an optional callback as the 2nd arg for customization
setupListeners(store.dispatch);
```
Thank You.
You can follow us on:
[Youtube ](https://www.youtube.com/c/ULTIMATEPROGRAMMING)
[Instagram](https://www.instagram.com/full_stack_web_developer1/)