React-query mutations , which perform create,update,delete operations on data easy to setup and invalidate query.

Preparing the create method

Usually it is done with API route, lets tear the mutation into two part the API createUser method and the Mutation.

export const createUser = async (usr:User) => {    const res = await fetch('http://localhost:3000/api/users', {      method: "POST",      body: JSON.stringify(usr),      headers: {        'Content-Type': 'application/json'      }    });

The mutation

Mutation can be create inside a functional component by using useMutation hook and our createUser helper function.

import {createUser } from '../hooks' import { useMutation } from 'react-query'; .....     const mutation = useMutation((formData) => {          return createUser(formData)      }); 

Use mutation and mutate as follows.

const usr = { name: values.name, email: values.email, cId: values.cid, lId: values.lid, secret: values.secret }                              mutation.mutate(usr, {              onSuccess: () => {                                    console.log('success');              }

We can use onSuccess function to implement our invalidation logic. Also it is possible to render logics such as

 return (       <div>         {mutation.isLoading ? (           'Adding User...'         ) : (           <>             {mutation.isError ? (               <div>An error occurred: {mutation.error.message}</div>             ) : null}                {mutation.isSuccess ? <div>Todo added!</div> : null}                            </>         )}       </div>     )

Hope this will help someone


This free site is ad-supported. Learn more