Search code examples
reactjsreact-nativereduxreact-redux

Redux state array won't restart to its initial values


I am using redux for my react native apps. I want to restart my redux state after user doing some action.

Here my initial state looks like

    initialState = {
            a: "",
            b: "",
            arrayC: [
             {
                x : "xValue",
                y : "",
                z : ""
             }
           ]
    }

After some user action, the state change its value to something like this

        {
                a: "ValueA",
                b: "ValueB",
                arrayC: [
                 {
                    x : "xValue",
                    y : "ValueY",
                    z : "ValueZ"
                 }
               ]
        }

I have action to reset current state to initial state like before, this is my action for reset

export const resetStateReducer = () => ({
    type: RESET_STATE
});

and inside my reducer

case RESET_BOOKING_REDUCER:
            return initialState;

Everything works fine, except for arrayC. It still hold the values before reset, like this

{
            a: "",
            b: "",
            arrayC: [
             {
                x : "xValue",
                y : "ValueY",
                z : "ValueZ"
             }
           ]
    }

What should I do? is my code or logic is wrong?

Thanks

EDIT This is my action code for update arrayC value

case ADD_ARRAY_C:
            var { index, newObject} = action.payload;
            var temp = state.arrayC;
            temp[index] = { ...temp[index], ...newObject};

            return {
                ...state,
                arrayC: temp,
            };

Solution

  • Most likely your initial state is being mutated. Try to console log before you reset state and see what shows up.

    How do I correctly clone a JavaScript object?

    Check this out for how to clone an object for your initial state in the reducer.