Tuesday, March 6, 2018

Doctor-up collections in a reducer of Redux in an Angular 4 application without mutating state by dropping and recreating collections.

Below we are altering only the answers in the collection of answers that have changes and we are not adding items to unsavedAnswers that are already in the collection as we don't want dupes.

      case PLAN.UPDATE_ANSWERS:
         const updateAnswerAction = <UpdateAnswersAction>action;
         return {
            ...state,
            answers: state.answers.map((answer: PlanAnswerModel) => {
               const match = (updateAnswerAction.model.find(q => q.question.id ===
                     answer.questionId));
               return (match) ? {
                     ...answer,
                     value: match.answer,
                     skipped: match.skipped
                  }
                  : answer;
            }),
            unsavedAnswers: [
               ...state.unsavedAnswers.filter(x => !updateAnswerAction.model.some(y =>
                      y.question.id === x.question.id)),
               ...updateAnswerAction.model
            ]
         };
      default:
         return state;
   }
}

No comments:

Post a Comment