DEV Community

Cover image for Mutations
Nischal Dutt
Nischal Dutt

Posted on

Mutations

Over the past lessons, we went through the data fetching aspect of React Query now it's time to focus on the data hosting aspect i.e. interacting with the back-end of the application.

Unlike queries, mutations are typically used to create, update and delete data or perform server side-effects. These CRUD operations are pretty basic in any application that interacts with the back-end and React Query not only takes care of all such scenarios effectively but also goes the extra mile to make things simpler.

Here we’ll focus on how to perform a basic POST request and then gradually we’ll go through various features that are provided to perform these operations.

Consider from our previous example, /companies endpoint that returns a list of companies from the back-end. Now we will perform a POST request using Axios library, on this endpoint that will take the company’s name and its CEO’s name and will insert it into the list of companies.

For this purpose, React Query exports the useMutation hook.

import React from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useMutation } from "@tanstack/react-query";

import CompaniesList from "./CompaniesList";

const addCompany = (newCompany) => {
  return axios.post("http://localhost:4000/companies", newCompany);
};

const Mutations = () => {
  const [name, setName] = React.useState("");
  const [ceo, setCeo] = React.useState("");
  const { mutate: insertNewCompnay } = useMutation(addCompany);

  const addCompanyData = () => {
    insertNewCompnay({ name, ceo });
  };

  return (
    <div>
      <h1>enter company details</h1>
      <h2>name</h2>
      <input
        type="text"
        onChange={(e) => setName(e.target.value)}
        value={name}
      />
      <h2>ceo</h2>
      <input type="text" onChange={(e) => setCeo(e.target.value)} value={ceo} />

            <br />
      <button type="submit" onClick={addCompanyData}>
        save
      </button>
            <br />
      <CompaniesList />
    </div>
  );
};

export default Mutations;
Enter fullscreen mode Exit fullscreen mode

The useMutation hook takes a functions as its first argument and returns an asynchronous function called mutate which in-turn take our request body parameters and performs the insertion to the list of companies.

insert using useMutation

That’s how we perform CRUD operations using React Query, but there’s room for improvement. Notice each time we perform an insert we need to manually trigger a re-fetch for /companies by clicking on the button.

This is because the /companies query data is out of date but it will not get updated until its stale time is over. To overcome this we can manually inform that this particular query data is stale now and it needs to be updated.

For this scenario, the useMutation hook takes in a second argument object where we supply an onSuccess callback which will be called once the addCompany function is done executing.

import { useMutation, useQueryClient } from "@tanstack/react-query";

const queryClient = useQueryClient();
const { mutate: insertNewCompnay } = useMutation(addCompany, {
    onSuccess: () => queryClient.invalidateQueries("companies"),
});
Enter fullscreen mode Exit fullscreen mode

Now here we can make use of invalidateQueries function which is available via the queryClient object which takes in the query key that needs to be updated. When the invalidateQueries function is called, the stale time of the query is set to the EXPIRED state and the query is re-fetched automatically in the background.

invalidating queries


Thank you for reading!

And that's a wrap for this series. Now we know why React Query is considered as The Missing data fetching Library.
Go ahead and start experimenting.

And as always, feel free to reach out to me! 😊

💻 Github ✨ Twitter 💌 Email 💡Linkedin

Happy Conding!

Top comments (0)