0

Here's the final data signature that I am saving in redux store.

const finalDataFormInReduxStore = {
  "id": "123",
  "id_details": [
    {
      "user_city": "SF",

    },
    {
      "user_city": "SF",
    }
}

Here's my simple action

export const updateUserCity = (index, city) => {
  return {
    type: UPDATE_USER,
    payload: {
      index,
      city
    }
  };
};

The following reducer works where I am making the id_details property to be an object (but I wanted this prop to be an array as per my target data signature in redux store. )

case UPDATE_USER :  {
  return {
    ...state,
      id_details: {
        ...state.id_details,
        [actions.payload.index]: {
          ...state.id_details[actions.payload.index],
          user_city: actions.payload.city
        }
      }
  };
}

But, when I make id_details property to be an array the following reducer does NOT work . (which is what I wanted as per my target data signature in redux store. )

case UPDATE_USER :  {
  return {
    ...state,
      id_details: [
        ...state.id_details,
        [actions.payload.index]: {
          ...state.id_details[actions.payload.index],
          user_city: actions.payload.city
        }
      ]
  };
}

I have looked at this github issue page for guidance, but did not help me . Probably I am missing something basic here.

2
  • When you say it doesn't work, what specifically isn't working? What error are you receiving? Can you provide the action for UPDATE_USER instead of UPDATE_USER_CITY? Commented Aug 12, 2019 at 8:27
  • 1
    @DrewReese I corrected the action for UPDATE_USER instead of UPDATE_USER_CITY. Commented Aug 12, 2019 at 8:54

1 Answer 1

2

From https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#updating-an-item-in-an-array the easiest way to do this is by mapping over the array:

case UPDATE_USER : {
  return {
    ...state,
    id_details: state.id_details.map((item, index) => {
      if (index === actions.payload.index) {
        return {...item, user_city: actions.payload.city};
      }
      return item;
    }),
  };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.