How to Use React 18 Query Mutation to Create or Add Data to Server

Last Updated on by in React JS

React Query Mutation Query example. In this post, you will comprehend how to create or add data to the server using React Query’s useMutation hook in React JS app.

Mutations provide a system to post data to the server and perform server-side effects.

This guide will respectively walk you through every step essential to add data to the server with an Axios Post request.

We will create a React app, create a function component, set up bootstrap, and, most importantly, React Query library.

We will then register the React Query module in our React app. This process will give us access to use React queries and the useMutation hook.

Generally, queries are used to retrieve or fetch the data from the server. But how about dealing with post, delete, or update the data through react query?

In that very situation, mutation comes into play. Mutation lets you trigger server-side effects.

A mutation is performed to manage the global server state, and it gives you access to the following states:

isIdle or status === ‘idle’ – The mutation is currently idle or in a fresh/reset state.

isLoading or status === ‘loading’ – The mutation is currently running.

isError or status === ‘error’ – The mutation encountered an error.

isSuccess or status === ‘success’ – The mutation was successful, and mutation data is available.

How to Post Data to Server using Mutation in React with React Query

  • Step 1: Build React Project
  • Step 2: Add Axios & React Query
  • Step 3: Configure Bootstrap Module
  • Step 4: Setting Up React-Query
  • Step 5: Build Function Component
  • Step 6: Create JSON Server
  • Step 7: Post Data to Server with useMutation
  • Step 8: Update App JS Component
  • Step 9: Test App on Browser

Build React Project

The Create React App tool is an imperative tool to create React app that you must have along with Node and NPM on your system.

After running the given command, you will have to move into the project’s root.

npx create-react-app react-blog-app
cd react-blog-app

Add Axios & React Query

Axios helps you make the request to the server, whereas Request query offers you unconditional support to handle the server response.

Here is how you can use the given command to add both packages to your React app.

npm install @tanstack/react-query axios --legacy-peer-deps

Configure Bootstrap Module

The bootstrap framework supports you with creating the UI at rapid speed in your application.

You won’t have to put in additional effort to create the UI components.

npm i bootstrap --legacy-peer-deps

There comes the second step, where you need to import bootstrap css in src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

function App() {
  return <div></div>;
}

export default App;

Setting Up React-Query

Import QueryClientProvider and QueryClient from the react-query package; wrap the App component with QueryClientProvider module. Go ahead and replace the App.js code with given code.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Create a client
const queryClient = new QueryClient();

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

You are now ready to use all the hooks and mutation hook through the react-query module.

Build Function Component

You have to create the components/ directory, also the Users.js function component file.

import React from 'react'

function Users() {
  return (
    <div>Users page</div>
  )
}

export default Users

Create JSON Server

To create the JSON server we need to install the json-server module. Here is the command that you have to invoke to add the module globally.

sudo npm install -g json-server --legacy-peer-deps

Next, at the root of your React project you have to create the db.json file, make sure to add the following code to the file.

{
  "posts": [

  ]
}

Run the backend server on another terminal screen with given command; it will provide the api link on the console screen.

json-server --watch db.json --port 3004

Post Data to Server with useMutation

Here is the file where we are using the code to perform the mutation to add the data to server.

Make sure to place the code into the components/Users.js file.

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

function Users() {
  const mutation = useMutation((DATA) => {
    return axios.post("http://localhost:3004/posts", DATA);
  });

  return (
    <div>
      {mutation.isLoading ? (
        "Adding post..."
      ) : (
        <>
          {mutation.isError ? (
            <div>Error : {mutation.error.message}</div>
          ) : null}

          {mutation.isSuccess ? <div>Post added! </div> : null}

          <button
            onClick={() => {
              mutation.mutate({
                title:
                  "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
                body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
              });
            }}
          >
            Create Post
          </button>
        </>
      )}
    </div>
  );
}

export default Users;

Update App JS Component

We created the sole component therefore it has to be imported into the App.js file.

Replace your App.js file code with the following code.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import Users from "./components/Users";

function App() {
  return (
    <div className="container mt-5">
      <h2>React Query Fetch Data useMutation Example</h2>
      <Users />
    </div>
  );
}

export default App;

Test App on Browser

You have almost crossed all the hurdles that have come your way. The last task is to run the app server and run the app on the browser.

npm start
http://localhost:3000

How to Use React Query Mutation to Create or Add Data to Server

Conclusion

In this react query use mutation example, we learned how to use React query useMutation hook to post or create data to the server in React application.

We deeply looked at and shared the instructions that help you build a React app using React query.