Home > other >  POST method JSON not updating JSON server local file
POST method JSON not updating JSON server local file

Time:09-28

I have setup a POST method on the submit handler of my react app. But every time I submit the form, the JSON server just registers the id, and not the content, as shown below:

Output Image

Json Server local file

As you can see, the app can display the user input's newly submitted form, but it can't be registered in the json server, as it only shows the id. Here is the snippet for the Submit handler function of the form:

const formSubmitHandler = (event) => {
    event.preventDefault();

    if (!enteredFNameValid || !enteredLNameValid) {
      alert("First Name and Last Name accepts letters only.");
      return;
    }

    const newInputData = {
      fName: enteredFName,
      lName: enteredLName,
      email: enteredEmail,
      eid: enteredEid,
      birthday: enteredBirthday,
    };

    const allInputData = [...inputData, newInputData];

    setInputData(allInputData);

    // console.log(allInputData);

    fetch("http://localhost:3001/inputData/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify[newInputData],
    }).then((res) => {
      console.log("new post added");
      alert("Success!");
    });
};

I've tried to change the body to an object as {newInputData}, but it just creates a new set of array, and registers that as the new entry for the JSON's generated id.

Hope to have insights from ya'll. Thank you.

CodePudding user response:

Maybe it's an issue with square brackets on the JSON.stringify?

Did you take a look at this post?

  • Related