javascriptreactjsisomorphic-fetch-api

React Isomorphic Fetch not actually posting


I'm creating a website using React, one of the steps involves creating an event. I've created a step that posts to an API using isomorphic fetch.

import fetch from "isomorphic-fetch";

export function createEvent(data) {
    console.log(data);
    return fetch("whatson/createEvent.php", {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
            "Content-Type": "application/json"
        },
        redirect: "follow"
    }).then(response => {
        if (response.status >= 200 && response.status < 300) {
            alert("Success");
            console.log(response);
            return response;
        } else {
            console.log("Something went wrong");
            console.log(response);
        }
    });
}

I've stepped through the response and it says that it's A-OK, 200 response status etc, however, nothing actually gets added to the database.

If I use the same data that is posted and call the same API address in postman it works fine and the data is added to the database so I'm fairly confident that it's not the API itself and more something to do with the above code.


Solution

  • Probably, you need to return response.json():

    import fetch from "isomorphic-fetch";
    
    export function createEvent(data) {
      console.log(data);
      return fetch("whatson/createEvent.php", {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json"
        },
        redirect: "follow"
      }).then(response => {
        if (response.status >= 200 && response.status < 300) {
          alert("Success");
          return response.json();
        } else {
          console.log("Something went wrong");
          console.log(response);
        }
      }).then(json => console.log(json));
    }