eymas
eymas

Reputation: 105

ReactJS: Reloading component after function is executed?

In the quest to make a to-do application in order to get more familar with API's, CRUD and React, I've encountered a slight roadblock on reloading the component(s) after executing a function.

The case is as following:

  1. Tasks get displayed
  2. User can press button to mark task as finished
  3. Task is marked as finished (This is already working)
  4. Button gets changed to "Mark unfinished" (This doesn't fire)

At the moment I use window.location.reload() to force each component to update after pressing the "mark finished" button, however I know that refreshing the entire page upon this is rather unnecessary, and to my understanding voids the whole reason of using javascript and react.

As such, I should be using this.setState() to do this instead, but it is not working without any explanation why. Neither would this.forceUpdate() which is discouraged to begin with.

The code is as following:

constructor(){
  super();
  this.state = {
    tasks: [],
    update: false
  }; 

  this.markFinished = this.markFinished.bind(this);
  this.update = this.update.bind(this);
}

markFinished(id, title, content){
  axios.put('/api/tasks/'+id, querystring.stringify({
    task_id: id,
    title: title,
    content: content,
    state: 'finished'
  }),{
    headers: {"Content-Type": "application/x-www-form-urlencoded"}
  })
  .catch(function(err){
    console.log(err)
  })
  this.setState({update: true}); 
}

Is there something that I would be missing in this implementation of setState? Oddly enough if I replace update: true with tasks: [] it will update, but remove the entire tasks array as result. prompting me that it -does- function as it should.

Upvotes: 1

Views: 604

Answers (1)

cbll
cbll

Reputation: 7219

You are running an async function with axios.put, so your update: true is executed before axios.put returns the promise, you likely want to do a .then(//set the state here) on success.

So, something along this line:

let that = this;
axios.put('/api/tasks/'+id, querystring.stringify({
    task_id: id,
    title: title,
    content: content,
    state: 'finished'
  }),{
    headers: {"Content-Type": "application/x-www-form-urlencoded"}
  })
  .then(function(success) {
    that.setState({update: true})
   }
  .catch(function(err){
    console.log(err)
  })

On success of your axios.put the state will be updated and your page should re-render.

Upvotes: 5

Related Questions