Reputation: 3017
I'm a beginner to Redux and having trouble.
Somehow after every action, my whole store is completely cleared and only current action is executed. I'm going to describe the situation with screenshot of action log.
Here is my action:
function writeProduct(id) {
return {
type: 'WRITE_PRODUCT',
id
}
}
Here is my reducer:
case 'WRITE_PRODUCT':
console.log("WRITE PRODUCT ACTION: ", action);
console.log("state: ",state);
return {
productID: action.id
};
And here is the consoled log during the dispatch
of writeProduct
action.
https://cdn1.imggmi.com/uploads/2018/5/9/c4cfc7debab662dfe241889d86254cd1-full.png
What I do wrong? Why after every dispatch previous store is overwritten?
Upvotes: 0
Views: 290
Reputation: 824
hmmm i don't know why the whole store is wiped out but
case 'WRITE_PRODUCT':
console.log("WRITE PRODUCT ACTION: ", action);
console.log("state: ",state);
return {
productID: action.id
};
should be
case 'WRITE_PRODUCT':
console.log("WRITE PRODUCT ACTION: ", action);
console.log("state: ",state);
return {
...state,
productID: action.id
};
```
state
is passed to your reducer function
Upvotes: 1
Reputation:
You're overwriting the previous state in your reducer. You should include all the previous state and only change what the reducer should.
Eg. In your reducer:
return {
...state,
productID: action.id
};
Notice the ...state
part, which includes all the previous state in the result.
I'd suggest you review the redux docs on immutable updates
Also, your action object isn't FSA compliant, should probably read about that too.
Upvotes: 3