Reputation: 21901
I have a simple two button on the web page one for increment and one for decrements an integer.
Once i click on + button it will add 1 to the current value.
Below is my Reducer and i have wrapped "INCREMENT" with a setTimeout
and when i click on + button i'am expecting to see 1 on the page after 2 secs, but it gives me 77 as soon as click happens without waiting for 2 secs, Why this happens, why 77 every time?
p.s. I might need a middleware to handle this async action, but i m trying to understand whats going on
Thank you
const mathReducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return setTimeout(() => {
state = state + 1
}, 2000)
case 'DECREMENT':
return state - 1
default:
return state
}
}
export default mathReducer
Upvotes: 0
Views: 468
Reputation: 11870
Because a reducer function works by deterministically returning the new value of the state, given the old state, and whatever action.
In your code you are just reassigning the state variable, with this line:
state = state + 1
If what you want to do is update the state after 1 second, what I would do is use the setTimeout to defer triggering the 'update state' action.
Upvotes: 2