Search code examples
angularngrxngrx-storengrx-effects

Reducer in NgRx takes old state after dispatching second action in a row


Every employee has many skills and it can be accessed with employee.skills, and I made logic to add, delete and update them.

Everything works perfectly except this situation: For instance let's say I add a skill. Ok skill gets added, component re-renders and skill is shown in the list. After that I update some other skill. This other skill gets updated, but the previously added skill gets deleted from the list. In Redux DevTools extension I see that update skill action took old state (the state before newly added skill) and just updated the other skill. BUT after I refresh the page, everything seems ok: New Skill is there and the other skill is updated. This happens no matter which action in which order is dispatched.

First action: Add skill

Second action: Update some other skill

Employee model:

export class Employee {
  id?: number;
  firstName: string;
  lastName: string;
  skills?: Skill[];

}

Solution

  • The problem seems to be in the UPDATE_SKILL_SUCCESS reducer function.

    The ADD_SKILL_SUCCESS function is adding the new skill to the skill property present in the EmployeeState. You are not adding it to the skill present within Employee object.
    Now, while updating the skill, you are getting the newState from the skills property of the Employee model (which does not have the newly added skill).

    So in order to get it working for you, you need to tweak your UPDATE_SKILL_SUCCESS reducer function a little bit.
    Replace the first line with let newState = state['skills']; and it should work for you.