Search code examples
javascriptreactjspostaxioscatch-block

Axios does not run - React JS


I am using axios to make a POST request with React JS, specifically a POST request to the Sendinblue API, found here. I have tried multiple variations using axios however I have not had any luck with successfully completing the POST request.

The code is listed below:

var email = this.state.value;
var data = JSON.stringify({ "listIds": [5], "email": email, "attributes": { "SMS": "sms-Number" }, "emailBlacklisted": false, "smsBlacklisted": false, "updateEnabled": true });
var config = {
     method: 'post',
     url: 'https://api.sendinblue.com/v3/contacts',
     headers: {
         'api-key': 'API-key',
          'Content-Type': 'application/json'
     },
     data: data
};

axios(config)
.then(function (response) {
     alert(JSON.stringify(response.data));
})
.catch(function (error) {
      alert(error);
});

I have imported axios and the required libraries at the top.

Given this code, I never get an alert when axios is executed. That is, I never get an alert for success or error. So, it seems as if it is not even running the axios part.

Any ideas on why this may be? Thank you!


Solution

  • Thanks everyone for your help. I was able to solve this error by placing the button that triggers this code outside of the form tag.

    OLD CODE (not working):

    <form>
        <TextInput></TextInput>
        <button onClick={this.runCode}>Click here</button>
    </form>
    

    NEW CODE (working):

    <form>
        <TextInput></TextInput>
    </form>
    <button onClick={this.runCode}>Click here</button>