How to post (api-crud) data in json server at react js

To fetch data from a JSON server in a React.js application, follow these steps:

JSON Server library :: 

1- Set Up JSON Server

If you haven't already set up a JSON server, install it globally:

npm install -g json-server

Create a db.json file with sample data ::
{
  "users": [
   
  ]
}

Start the JSON server :
json-server --watch db.json --port 5000  

Now your fake API is running at http://localhost:5000/users. 


2. Post Data from React.js

Using Fetch API

import { useState } from "react";

const AddUser = () => {
  const [user, setUser] = useState({ name: "", email: "" });

  const handleChange = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch("http://localhost:5000/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(user),
    });
    const data = await response.json();
    console.log("User added:", data);
    alert("data submited");
  };

  return (
    <div>
      <h2>Add User</h2>
      <form onSubmit={handleSubmit}>
        <input type="text" name="name" placeholder="Name"         onChange={handleChange} required />
        <input type="email" name="email" placeholder="Email"         onChange={handleChange} required />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default AddUser;

Download from GitHub