0

I have a state and function in a Class in React Native and I am using this to create a counter to keep count of the number of tasks completed. In my updateTaskCountHandler() function taskCount successfully counts +1 to the previous value but upon console logging the value after setting completeTasks to the new value it is not showing that completeTasks was successfully updated to a new value. How can I update the state of completeTasks correctly?

state = {
        
        completeTasks: 0
    }
updateTaskCountHandler (className) {
        
        let taskCount = 0;
        taskCount = taskCount + 1;
        
        this.setState({
            completeTasks: taskCount
        })
        console.log('completeTasks:' + this.state.completeTasks);
    }   

 <ScrollView style={styles.taskitems}>
                    
                    <TaskCard clicked={() => this.updateTaskCountHandler("task1")} id='task1' chore='Get Dressed'/>
</ScrollView>

Matt Laszcz
  • 373
  • 3
  • 20
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – glinda93 Apr 23 '21 at 03:26

3 Answers3

1

If you want to see the state result after your setState logic, you should log your state in setState callback because react's setState function is asynchronous.

Taehyun Hwang
  • 232
  • 1
  • 2
  • 10
1

Try using this.forceUpdate() after the this.setState function. This will cause React to actually re-render the parent component which will pass the new props to the child component

Finley
  • 166
  • 1
  • 8
  • I tried this but for some reason even tho my counter is at 0 initially it doesn't start counting to 1 until after the first iteration. I cant seem to figure out why. – Matt Laszcz Apr 24 '21 at 13:28
  • I actually see the problem. I have another if statement that checks if all tasks are complete then show an animation but this is not being called again automatically unless a button is pressed. SHould it be in component did mount so its always checking the state? – Matt Laszcz Apr 24 '21 at 13:59
1

If you want to see the change of state, you need to use callback as follows:

this.setState({
        completeTasks: taskCount
    },()=>{
      console.log('completeTasks:' + this.state.completeTasks);
})
Maneesh
  • 664
  • 5
  • 12