Update the Old and New Value in Redux

Viewed 142

I have a problem updating the old value of the array in my redux react app. I have successfully updated the new selected object true. I want to other object to set to false since I have set the another object to true.

const initialState = {
  annualPlans: [],
};

const planReducer = (state = initialState, action) => {
  switch (action.type) {
    case planConstants.UPGRADE_PLAN_SUCCESS:
      return {
        ...state,
        annualPlans: state.annualPlans.map((todo) =>
          todo.value === action.data.plan_id
            ? // transform the one with a matching id
              { ...todo, current: true }
            : // otherwise return original todo
              todo
        ),
      };
    default:
      return state;
  }
};
3 Answers

It seems like you want to return current set to false for the others:

          todo.value === action.data.plan_id
            ? // transform the one with a matching id
              { ...todo, current: true }
            : // otherwise return with current false
              { ...todo, current: false }

Id first create the new todos by looping though a map and then assign to the state

case planConstants.UPGRADE_PLAN_SUCCESS: {
    const newTodos = state.annualPlans.map((todo) => {
        if (todo.value === action.data.plan_id) {
           return { ...todo, current: true }; // if todo.id matched then set the current to true and return;
        }

        if (todo.current) {
            return { ...todo, current: false }; // else if current is already true, then false it and return
        }

        return todo; // else return original todo
   });

    return {
        ...state,
        annualPlans: newTodos
    };
}        
.....

This will optimize the rendering and prevent of looping multiple times.

No need to re create all todo items, if you use pure components then that will mess up this optimisation. You can just add a map to deal with resetting the current value:

const planReducer = (state = initialState, action) => {
  switch (action.type) {
    case planConstants.UPGRADE_PLAN_SUCCESS:
      return {
        ...state,
        annualPlans: state.annualPlans
          .map(
            (todo) =>
              todo.current
                ? { ...todo, current: false } //reset current to false
                : todo // no need to change this one
          )
          .map((todo) =>
            todo.value === action.data.plan_id
              ? // transform the one with a matching id
                { ...todo, current: true }
              : // otherwise return original todo
                todo
          ),
      };
    default:
      return state;
  }
};
Related