DEV Community

AKSH DESAI
AKSH DESAI

Posted on • Edited on

3

Redux Toolkit

Folder Structure

Folder Photo

Index.js

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>
);

Enter fullscreen mode Exit fullscreen mode

App.js

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;

Enter fullscreen mode Exit fullscreen mode

post.js

// 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;
Enter fullscreen mode Exit fullscreen mode

store.js

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);
Enter fullscreen mode Exit fullscreen mode

Thank You.
You can follow us on:
Youtube
Instagram

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs