in43sh
in43sh

Reputation: 933

React button connection with database through axios.post()

I have 4 inputs and button which takes all data from them and sends to my PostreSQL database through axios.post() request. Not clearly understand how .then() is working. So, here is my button code which just calls this.addNewPainting function:

<button onClick={ this.addNewPainting }>Submit</button>

Here is my addNewPainting function:

addNewPainting() {
  axios.post(`http://localhost:333/api/add`, {
    title: this.state.titleInput,
    year: this.state.yearInput,
    size: this.state.yearInput,
    location: this.state.locationInput
  })
  .then(function(response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

Before this project, I used to put response.data to the array with this.setState, but now I have the database and I'm just stuck.

Here is my controller function:

add_painting: (req, res, next) => {
  const db = req.app.get('db');
  const { title, year, size, location } = req.body;
  console.log(title, year, size, location);

  db.add_painting([ title, year, size, location ])
    .then( () => res.status(200).send() )
    .then( () => res.status(500).send() );
}

And the endpoint:

app.post('/api/add', paintings_controller.add_painting);

Upvotes: 0

Views: 3316

Answers (2)

ArCiGo
ArCiGo

Reputation: 198

For future reading (becase you requested it): I'm not an expert using promises, but it works similarly like the AJAX requests.

When you make a request to the server (GET, POST, PUT, etcetera), you're waiting for a response from this (a collection of data, a message, a succesful/unsuccesful POST/PUT/DELETE, etcetera). Depending of the response, you'll code the expected events (error, success, complete, etcetera).

In this case you're using axios, a new way to do AJAX requests. The equivalent way of the error/success/complete/... events is the then() function. Using this approach you can perform operations that makes new tasks or simply print a response message (in your case) of the server.

From MDN:

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

Let's suppose that we have this snippet of code in AJAX:

$.ajax(
{
    url : yourURL,
    type : 'POST',
    data : yourData,
    datatype : 'json',
    success : function(data) { 
        yourSuccessFunction(data); 
    },
    error : function(jqXHR, textStatus, errorThrown) { 
        yourErrorFunction(); 
    }
});

Using axios, you'll code something like this:

axios.post('/user', {
    YourData: yourData
}).then(() => { this.yourSuccessFunction() })
}).catch(() => { this.yourErrorFunction() });

Upvotes: 2

in43sh
in43sh

Reputation: 933

I just found the error. I was making a request to PORT 333 in my axios.post(), but the server was working on port 3333.

Upvotes: 1

Related Questions