Maboo Maboo - 2 months ago 26
React JSX Question

Clearing an array state in Redux

How do I clear an array state in Redux? I have an initial state of an empty array, and things are being added. I want to have an action that just clear it, I tried the following method but it gives me "Unexpected token" error about the "action.payload" I give to the CLEAR_THINGS action:

export default (state=[], action) => {
switch (action.type) {
case "RECEIVE_THING":
return [
...state,
action.payload
];
case "CLEAR_THINGS":
return {
...state,
action.payload // payload here is []...
};
default:
return state;
}}


It also throw the error if I just use [] instead of through action.payload.

DDS DDS
Answer
export default (state=[], action) => {
switch (action.type) {
    case "RECEIVE_THING":
        return [
            ...state,
            action.payload
        ];
    case "CLEAR_THINGS":
        return [];
    default:
        return state;
}}

The RECEIVE_THING action uses object spread notation to return a state that is an array ([]) which contains the prior state ([...state]) and adds to that a new item ([...state, action.payload]). The key/property name used for this new item is simply the next index of the array. It is, after all, an array.

In your code for CLEAR_THINGS you are creating an object ({}) that contains the old state (say it was ['item1']) and so it looks like { '0': ['item1'] }. Next you proceed to use object shorthand notation to add more state, but this requires you use a single identifier (a single word) but you're using a dotted notion (qualified identifier) to access a property. You're kind of instructing a propery named action.payload be created but this is illegal and this is where your error comes from. The reason it works in the case of the array is because only a value is needed in this case, since the key is derived from the index of the array.

What you want to do is always return the same kind of object, in your case, an array. By starting with return {, you're already going the wrong way.

Comments