1

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.

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

strangely enough, it returns "this is undefined" despite that i've bound the function in the constructor already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.