Search code examples
javascriptjsonreact-nativefetchjson-server

Unable to perform POST request with fetch in react native


I am attempting to perform a POST operation on a json file being served by a json-server in node. I am receiving the following 500 error when attempting to perform said POST operation:

"TypeError: Cannot read property 'id' of undefined at Function.createId"

The post operation is as follows:

pushState = () => {
        var update = {
            "a": 1,
            "b": 2
        };

    return fetch(url, {
      mode: 'cors',
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(update)
    })
    .then((response) => {
      console.log(response);
      response.text();
    })
    .then((responseData) => {
      console.log("Response:",responseData);
    }).catch((error) => {
      console.log(error);
    })
    .done();
  }

Am I impementing the POST request correctly?

Edit: After adding async and await I'm still getting the same error:

pushState = async () => {
  var update = {
    "a": 1,
    "b": 2
  };

  var result = await fetch(url, {
    mode: 'cors',
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(update)
  })
  .then((response) => {
    console.log(response);
    return response;
  })
  .catch((error) => {
    console.log(error);
  });

  return result;
}

Solution

  • Two issues here:

    1. You are not returning anything from fetch.
    2. fetch is asynchronous. With the way you are calling it now with pushState returning a result immediately, it will almost always return undefined as you are getting in your error. You need write pushState using async/await.

    Edit to answer comments:

    Since you are using the function arrow syntax, making pushState asynchronous would look like this:

    pushState = async () => { /* code */ }
    

    To help you understand how fetch works, I recommend reading this first. Then to understand async/await at a high level, read this article. Your resulting code will look something like this:

    pushState = async () => {
      var update = {
        "a": 1,
        "b": 2
      };
    
      var result = await fetch(...) // Remember to return something.
    
      return result;
    }