In React I am trying to make a button increment a value stored in state. However using the code below function my value is set undefined or NaN when using handleClick.
Because you are using the handleClick function incorrectly. Here:
handleClick = (prevState) => { .... }
prevState
will be an event object passed to handleClick function, you need to use prevState with setState, like this:
handleClick = () => {
this.setState(prevState => {
return {count: prevState.count + 1}
})
}
Another issue is, setState is async so console.log(this.state.value)
will not print the updated state value, you need to use callback function with setState.
Check more details about async behaviour of setState and how to check updated value.
Check the working solution:
class App extends React.Component {
constructor(props){
super(props);
this.state={ count: 1}
}
onclick(type){
this.setState(prevState => {
return {count: type == 'add' ? prevState.count + 1: prevState.count - 1}
});
}
render() {
return (
Count: {this.state.count}
)
}
}
ReactDOM.render(
,
document.getElementById('container')
);