Search code examples
react-nativecountersetstate

React Native state not updating after using setState()


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>


Solution

  • 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);
    })