Matt Laszcz
Matt Laszcz

Reputation: 409

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>

Upvotes: 0

Views: 90

Answers (3)

Maneesh
Maneesh

Reputation: 674

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

Upvotes: 1

Finley
Finley

Reputation: 176

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

Upvotes: 1

Taehyun Hwang
Taehyun Hwang

Reputation: 260

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.

Upvotes: 1

Related Questions