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

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

by Shahriar Sagor

Hello dev’s , today now in this post i will show you How to Use React Query Mutation to Create or Add Data to Server. This is React Query Mutation Query example. Now in this post, i will comprehend how to create or add data to the server by using React Query’s useMutation hook in React JS app. So Mutations is provide a system to post data to the server and also perform server-side effects. Now this guide will respectively walk you through every step essential to add data to the server also with an Axios Post request.

Here i will create a React app, create a function component, set up bootstrap, and, most importantly, React Query library. Now i will then register the React Query module in our React app. So in this process i 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 also how about dealing with post, delete, or update the data through react query?

Now in that very situation, mutation comes into play. Mutation lets you trigger the 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 to Create or Add Data to Server

  • 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

Step 1: 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

Step 2: 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

Step 3: Configure Bootstrap Module

The bootstrap framework supports you with creating the UI at rapid speed in your applicaiton. You won’t have to put in additional effort to create the UI components.

npm i bootstrap

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;

Step 4: 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.

Step 5: 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

Read Also: React JS Build Multiple Checkbox with TypeScript Tutorial

Step 6: 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

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

Step 7: 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;

Step 8: 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;

Step 9: 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

Read Also: React JS Fetch, and Cache Data using React Query Tutorial

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like