ahh2
ahh2

Reputation: 13

Send data back to React client from Node server with POST request

A very simple counter application using React and Nodejs. In the client side, I have a counter component which consists of a count state and rendering on the UI with default value of 0 and each time user presses the increment button, it'll trigger a POST request API to node server. Then node server will then process the request and respond to the client with its result. How would I accomplish this?

Client side (Counter component)

this.state = {
   count : 0
}

sendAPI() {
   axios.post('http://localhost:3001/increment', this.state.count)...
}

render() {
    <div>
        <button onClick = {this.sendAPI()} type="button">increment</button>
        Counter: {this.state.count}  
    </div>
}

Server side (express server)

app.post('/increment', function(req,res) {
     res.send(req.body.count + 1)
}

How do I res.send() data back to "this.state.count" on the client side?

Upvotes: 1

Views: 1973

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

In the button onClick don't call the function, but pass the function as a reference.

state = {
   count : 0
}

sendAPI() {
   axios.post('http://localhost:3001/increment', {count: this.state.count})
       .then(res => {
               const count = res.data;
               this.setState({count: +count})
           );
}

render() {
    <div>
        <button onClick = {this.sendAPI} type="button">increment</button>
        Counter: {this.state.count}  
    </div>
}

Server side (express server)

app.post('/increment', function(req,res) {
     res.send(+req.body.count + 1)
}

Upvotes: 0

Related Questions