1

I am having some difficulties with Reactjs lifecycles. I have my front-end and back-end all set up but I can't figure out how to re-render the latest data after submitting a new data through POST request.

I am currently using componentWillMount to display all initial data from my database

componentWillMount(){
  axios.get('localhost:####/api/)
   .then(res =>{
     this.setState({
       listOfData:res.data
     })
   })
}

I have an addData function which sends a POST request to my database

addData(){
  let newData = 'string';
  axios.post(localhost:####/api, newData)
}

Now I know that we can just assign my listOfData from the GET request as a variable and push the new recipe into the state array(listOfData) to display it in our front-end, however my table in my database has an id increments and a timestamp thus if I wanted to update or delete my latest data it would cause an error. It cannot read the id value which makes sense since I did not assign the id in my POST request.

The only way I can display the new data from my database is to refresh the page which defeats the purpose. Do I have to include an id and timestamp from my front-end then in order to target the right id? There has to be a way to re-render my page and update the listOfData without refreshing it.

I've tried the following

componentWillUpdate(){
  axios.get('localhost:####/api/)
   .then(res =>{
    this.setState({
     listOfData:res.data
    })
   })
}

but this def isn't the right way.

  • You're missing a trailing single quote (`'`) in your call to `axios.get()`. Is this a copy/paste error, or is it present in your code? – esqew Apr 09 '18 at 22:40
  • What is your server responding to your `POST` request? – Axnyff Apr 09 '18 at 22:40

1 Answers1

1

What you would normally do, is have the server return the new item from the POST request (which would then include the ID and timestamp), and then insert it into your list:

axios.post('localhost:####/api', newData).then((response) => {
    var newItem = response.data;
    var listOfData = [...this.state.listOfData];
    listOfData.push(newItem);
    this.setState({listOfData: listOfData});
});
dave
  • 62,300
  • 5
  • 72
  • 93