Search code examples
javascriptnode.jsreactjsrefreshpage-refresh

How to refresh React page/component on Button click after POST


I want a table of data to refresh on button click after the POST request has been submitted.

I have a react button:

<Button onClick={this.click} className="domain-button" type='primary'>Add</Button>

And the corresponding click function, and refreshPage function:

async click() {
  const { domainInputValue } = this.state;
  console.log( domainInputValue );

  const response = await
  fetch('/new-cert', {
      headers: {
          'Content-Type': 'application/json'
      },

      method: 'POST',
      body: JSON.stringify({domainInput: domainInputValue})
  });

  const body = await response.text()
  console.log(body)

  if (response.status !== 200) throw Error(body.message);
  return body;
}

refreshPage() {
  window.location.reload();
}

And in my back-end Nodejs to handle the POST request I have:

app.post('/new-cert', function (req, res) {
    fs.appendFile('certs-list', '\n' + req.body.domainInput, function (err) {
        if (err) throw err;
    });
    res.send('POST request: ');

    console.log("INSERTING")
    exec('sh cert-check-script-insert.sh');

    console.log(req.body);
    console.log('post is working!')
});

I'm not sure where to call refreshPage(), I've tried calling it right after click() but this seems to be too early and the refresh does not change the data displayed in the table.


Solution

  • I ended up adding a function componentDidUpdate() which mimics my componentDidMount() behaviour:

    componentDidMount() {
        this.callApi()
            .then(res => {
                this.setState({
                    json: res.map(x => x),
                })
            })
            .catch(err => console.log(err));
    }
    
    
    componentDidUpdate() {
        this.callApi()
            .then(res => {
                this.setState({
                    json: res.map(x => x),
                })
            })
            .catch(err => console.log(err));
    }