M
M
Moro Zota2018-05-29 22:25:02
Node.js
Moro Zota, 2018-05-29 22:25:02

How to update a component?

API node:

var express = require('express');
var router = express.Router();

var ch = 0
router.post('/', function(req, res) {
  ch += 1
  res.json({
    ch
  })
})

router.get('/c', function(req, res, next) {
  res.json(
    ch
  )
})

module.exports = router;

react component:
import React, { Component } from 'react';
import './App.css';

class App extends Component {
    state = {
        count: []
    }

    componentDidMount() {
        fetch('/users/c')
            .then(res => res.json())
            .then(count => this.setState({ count }));
    }

    render() {
        return (
            <div>
                {this.state.count}
                <button onClick={this.add}>add</button>
            </div>
        )
    }
    add = () => {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/users/');
        xhr.send();
    }
}

export default App;

I receive a zero from the server and display. then when I click on the `add` button, I pull the POST request to add one. One is added, but what would be displayed, you need to refresh the page. Probably it is necessary to do something with setState. but I don't understand what

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-05-29
@morozota

add = () => {
  fetch('/users/', { method: 'POST' })
    .then(res => res.json())
    .then(count => this.setState({ count }));
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question