DEV Community

Cover image for Redux-Toolkit CRUD QUICK OVERVIEW
NISHARGA KABIR
NISHARGA KABIR

Posted on

Redux-Toolkit CRUD QUICK OVERVIEW

Here, I am giving you a quick overview of Redux Toolkit use cases and performing a CRUD operation. I tried to keep it as brief as possibleโœ…

I will start directly here. Iโ€™ve skipped the Redux Toolkit setup as well. I suggest that after reading this, you follow a playlist or take a crash course to learn, and also refer to the documentation for further learning. Letโ€™s start the game! ๐Ÿ˜๐Ÿ˜๐Ÿ˜

UnderStand concept

In Redux Toolkit or Redux, you may see two things:

1.Endpoint Type
2.Tags

Two endpoint types are in the redux toolkit. One is a query, and the other is a mutation. In Redux.... getAll or singleGet is called a query; without this, everything else is called a mutation.

You have to pass a tag inside every API route invalidatesTags or providesTags.
For queries, we use providesTags, which acts like an ID that we set for later use. For mutations, we use invalidatesTags, which simply call back the provided tag.
This means that after completing an /update, /delete, or /post route, the /get or /getAll route is automatically fetched, so we donโ€™t need to refresh to see the updated data. โœ…

Step 0: Boilerplate create

inside feature folder, i create driverSalaryApi.ts You can create as your wish ๐Ÿ™‚

import { baseApi } from "../baseApi";

const driverSalaryApi = baseApi.injectEndpoints({
  endpoints: (build) => ({
    // ALL CODE WILL WRITE HERE
  }),
});


export const {  } = driverSalaryApi;
Enter fullscreen mode Exit fullscreen mode

This is very basic structure. just create a variable and inject BaseApi. finally export it. โœ…โœ…

Step 1: C for Create ๐Ÿ˜…

createDriverSalary: build.mutation({
      query: (data: any) => ({
        url: `/driver-salary/create`,
        method: "POST",
        data: data,
      }),
      invalidatesTags: ['salary'],
    }),
Enter fullscreen mode Exit fullscreen mode

Using the build.mutation method, we can create anything. The baseURL is already added in the baseHome, so we donโ€™t need to add the full URL repeatedly. Only just the endpoints. Finally export it.

export const { useCreateDriverSalaryMutation } = driverSalaryApi;
Enter fullscreen mode Exit fullscreen mode

After typing use and the variable name, it will auto-import, so there's no need to worry about it.

Now just go to your page.tsx where you use this โœ…

const [createDriverSalary] = useCreateDriverSalaryMutation();
Enter fullscreen mode Exit fullscreen mode

import that mutation and use it

const onSubmit = async (data: any) => {
    try {
      const res = await createDriverSalary(data);
      if(res){
        console.log("res:", res)
      }
    } catch (error) {
      console.log("driver salary error", error);
    }
  };
Enter fullscreen mode Exit fullscreen mode

Step 2: R for Read ๐Ÿ˜…

This is a getAll route.

getAllDriverSalary: build.query({
      query: (page) => ({
        url: `/driver-salary/list`,
        method: "GET",
      }),
      providesTags: ['salary'],
    }),
Enter fullscreen mode Exit fullscreen mode

and export like this.

export const { useGetAllDriverSalaryQuery } = driverSalaryApi;
Enter fullscreen mode Exit fullscreen mode

Now go to page.tsx and import our created query โœ…

const { data: salaryDriver, isFetching, isLoading, } = useGetAllDriverSalaryQuery("");
Enter fullscreen mode Exit fullscreen mode

finally console.log salaryDriver you will see the result..

getSingle

getSingleDriverSalary: build.query({
      query: (id: any) => ({
        url: `/driver-salary/single/${id}`,
        method: "GET",
      }),
      providesTags: ['salary'],
    }),
Enter fullscreen mode Exit fullscreen mode

and export it

export const { useGetSingleDriverSalaryQuery } = driverSalaryApi;
Enter fullscreen mode Exit fullscreen mode

finally go to that page.tsx โœ…

const { data: driverSalarySingle } = useGetSingleDriverSalaryQuery("SINGLE ID PASS HERE");
Enter fullscreen mode Exit fullscreen mode

For the getSingle route, we just need to pass the ID. The rest is the same as getAll. We can also use isLoading, isFetching, or isError here. For more information, you can refer to the documentation.

Step 3: D for Delete๐Ÿ˜…

deleteDriverSalary: build.mutation({
      query: (id: any) => ({
        url: `/driver-salary/delete/${id}`,
        method: "DELETE",
      }),
      invalidatesTags: ['salary'],
    }),
Enter fullscreen mode Exit fullscreen mode

And export it

export const { useDeleteDriverSalaryMutation } = driverSalaryApi;
Enter fullscreen mode Exit fullscreen mode

And in the page.tsx โœ…

const [deleteDriverSalary] = useDeleteDriverSalaryMutation();
Enter fullscreen mode Exit fullscreen mode

finally, use a handler function.

const onHandleDelete = async (data: any) => {
    try {
      const res = await deleteDriverSalary("DELETE ID");
      if(res){
        console.log("res:", res)
      }
    } catch (error) {
      console.log("driver salary error", error);
    }
  };
Enter fullscreen mode Exit fullscreen mode

Step 4: U for Update๐Ÿ˜…

Remember that for updates, you need the ID as well as the updated data.

updateSingleUse: build.mutation({
            query: ({ id, ...data }) => ({
                url: `vehicle/update/${id}`,
                method: 'PATCH',
                data: data
            }),
            invalidatesTags: [tagTypes.user]
})
Enter fullscreen mode Exit fullscreen mode

For updates, look at the method. If your backend API uses the PUT method, then use PUT, and if it uses the PATCH method, then use PATCH.

export const { useUpdateDriverSalaryMutation } = driverSalaryApi;
Enter fullscreen mode Exit fullscreen mode

And uses

const [updateSingleUser] = useUpdateSingleUseMutation();
Enter fullscreen mode Exit fullscreen mode

Then collect the updated data. Here, Iโ€™m using a simple variable, but in a real-life scenario, you would get your data from a form.

const updateData = {
        price: 10000,
        tax: 1000
    };
Enter fullscreen mode Exit fullscreen mode

Finally, Now we will use handler function to trigger the API.

const handleUpdateData = async () => {
        const res = await updateSingleUser({
            id: '65d098133a2e34cc13f13551',
            ...updateData
        });
        console.log(':rocket: ~ handleUpdateData ~ res:', res);
    };
Enter fullscreen mode Exit fullscreen mode

I hope you now have an idea of how to use Redux Toolkit. Thanks for reading. โ˜‘โ˜‘โ˜‘

Top comments (1)

Collapse
 
blackdream profile image
MohammedHamim

awsome