简体   繁体   中英

React JS + Fetch API Posting

I using the fetch API to post some data from a form, that works.

However I'm facing an issue, the issue is when I post data the state doesn't update, Yes I know I'm not using the setState() but there's nothing set it to. yet.

Currently I'm attempting to debug the issue by console logging, and it turns out the body isn't been used.

Submit Function :

addContact = (event) => {

      event.preventDefault(); //Prevents The Default Action Of A Form


      const formData = {};

      /* 
      for(let [temp variable] in this.state.contacts) {
        formData[attach temp variable] = to contacts[temp variable].value
      }

      */

      // BASIC TERM: For everything in the contacts config set the formData (Blank Object) equal to the identifier e.g. name, street equal to the state value. The object will then be populated
      // The formData is then attached to an object named object and sent to the firebase database by attaching it to the post request
      for(let formElementIdentifier in this.state.contacts) {
        formData[formElementIdentifier] = this.state.contacts[formElementIdentifier].value;
      }

      const data = {
        persons: formData
      }

      fetch("https://address-book-database.firebaseio.com/contact.json", {
        method: "POST",
        headers : {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
      .then((res) => {
        console.log("Body Used Or Not")
        console.log(res.bodyUsed)
      })
      .then(json => {

      })
    }

This is the first time using the fetch API. Tm really confused why this wont work, any help would greatly be appreciated. Im aware of chaining .then() but I couldnt get it to work with the POST requet.

All I want to do is set the values from my form and attach it to the request, the request needs to be converted to JSON, then the state needs to be updated.

Full Project : https://github.com/AlexMachin1997/React-JS-Contact-Book/blob/master/src/Components/Contact/Contacts/Contacts.js

Use your fetch request like below. You need to use response.json(). It waits for the body to load.

Why does response.json return a promise?

Because you receive the response when all headers have arrived. Calling .json() gets you a promise for the body of the http response that is yet to be loaded

Why is the response object from JavaScript fetch API a promise?

fetch('https://address-book-database.firebaseio.com/contact.json', {
    method: 'post',
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify(data)
}).then(function (response) {
    return response.json(); //response.json() is resolving its promise. It waits for the body to load
}).then(function (responseData) {
    //Do your logic
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM