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;
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'],
}),
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;
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();
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);
}
};
Step 2: R for Read ๐
This is a getAll route.
getAllDriverSalary: build.query({
query: (page) => ({
url: `/driver-salary/list`,
method: "GET",
}),
providesTags: ['salary'],
}),
and export like this.
export const { useGetAllDriverSalaryQuery } = driverSalaryApi;
Now go to page.tsx and import our created query โ
const { data: salaryDriver, isFetching, isLoading, } = useGetAllDriverSalaryQuery("");
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'],
}),
and export it
export const { useGetSingleDriverSalaryQuery } = driverSalaryApi;
finally go to that page.tsx โ
const { data: driverSalarySingle } = useGetSingleDriverSalaryQuery("SINGLE ID PASS HERE");
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'],
}),
And export it
export const { useDeleteDriverSalaryMutation } = driverSalaryApi;
And in the page.tsx โ
const [deleteDriverSalary] = useDeleteDriverSalaryMutation();
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);
}
};
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]
})
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;
And uses
const [updateSingleUser] = useUpdateSingleUseMutation();
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
};
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);
};
I hope you now have an idea of how to use Redux Toolkit. Thanks for reading. โโโ
Top comments (1)
awsome