Reputation: 199
my hook useState change state just once, all the time i have 1. How can i fix it ?
const My = () => {
const [state,setState] = useState({
count : 0
})
useEffect(() => {
console.log(state);
},[state]);
return (
<div>
<h1>{state.count}</h1>
<button onClick={()=> setState(prevState => ({
...prevState,
count: +1
}))}>Click</button>
</div>
);
};
Upvotes: 2
Views: 342
Reputation: 188
There is a syntax error in your code: count: +1
.
So, the quick fix is this:
const My = () => {
const [state,setState] = useState({
count : 0
})
useEffect(() => {
console.log(state);
}, [state]);
return (
<div>
<h1>{state.count}</h1>
<button onClick={()=> setState(prevState => ({
...prevState,
count: prevState.count + 1
}))}>Click</button>
</div>
);
};
However, your code can be simplified a lot. This will output the exact same thing:
const My = () => {
const [count, setCount] = useState(0);
console.log(state);
return (
<div>
<h1>{state.count}</h1>
<button onClick={()=> setCount(count + 1)}>Click</button>
</div>
);
};
Upvotes: 2
Reputation: 5380
Here is the problem ()=> setState(prevState => ({ ...prevState, count: +1 }))
and can be fixed this way:
onClick={() =>
setState(prevState => ({
...prevState,
count: prevState.count+1
}))
}
Upvotes: 1