Blog>
Snippets

Performing CRUD Operations with Mutation Endpoints

Code example showing how to create mutation endpoints for creating, updating, and deleting resources (e.g., `addUser`, `updateUser`, `deleteUser`) and using the respective auto-generated mutation hooks in a React component.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const userApi = createApi({
  reducerPath: 'userApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com' }),
  tagTypes: ['User'],
  endpoints: (builder) => ({
    addUser: builder.mutation({
      query: (user) => ({
        url: '/users',
        method: 'POST',
        body: user,
      }),
      invalidatesTags: ['User'],
    }),
    updateUser: builder.mutation({
      query: ({ id, ...rest }) => ({
        url: `/users/${id}`,
        method: 'PUT',
        body: rest,
      }),
      invalidatesTags: ['User'],
    }),
    deleteUser: builder.mutation({
      query: (id) => ({
        url: `/users/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['User'],
    }),
  }),
});

export const { useAddUserMutation, useUpdateUserMutation, useDeleteUserMutation } = userApi;
Defines a 'userApi' service with mutation endpoints for adding, updating, and deleting users. Also exports auto-generated hooks for these mutations.
import React from 'react';
import { useAddUserMutation, useUpdateUserMutation, useDeleteUserMutation } from './services/userApi';

function UserComponent() {
  // Hooks for mutation
  const [addUser] = useAddUserMutation();
  const [updateUser] = useUpdateUserMutation();
  const [deleteUser] = useDeleteUserMutation();

  // Example function call to add a user
  const onAddUser = async () => {
    try {
      const newUser = { name: 'John Doe', email: 'john@example.com' };
      await addUser(newUser).unwrap();
      // Handle successful add here
    } catch (error) {
      // Handle add error here
    }
  };

  // Example function call to update a user
  const onUpdateUser = async (userId) => {
    try {
      const updatedData = { name: 'Jane Doe' };
      await updateUser({ id: userId, ...updatedData }).unwrap();
      // Handle successful update here
    } catch (error) {
      // Handle update error here
    }
  };

  // Example function call to delete a user
  const onDeleteUser = async (userId) => {
    try {
      await deleteUser(userId).unwrap();
      // Handle successful delete here
    } catch (error) {
      // Handle delete error here
    }
  };

  return (
    <div>
      {/* UI components to interact with user CRUD operations */}
    </div>
  );
}

export default UserComponent;
Implements a React component that uses the auto-generated hooks to add, update, and delete users. Includes example function calls with error handling.