2

In a NgRx Angular 5 project, there is a use of the reduce function i don't really understand. I would appreciate some help

Basically the code iterates an array of object and the array looks like this:

[{
   id: '0',
   message: 'work',
   done: false
 },
 {
   id: '1',
   message: 'movie',
   done: false
 },
 {
   id: '2',
   message: 'Play',
   done: false
 }]

In my NgRx reducer, there is the following block of code :

case todosAction.FETCH_TODO_SUCCESS: {
  return {
    ...state,
    //action.payload contains above array of objects
    datas: action.payload.reduce((accumulateur, iteration) => {
      accumulateur[iteration.id] = iteration;
      return accumulateur;
    }, { ...state.datas }),
    loading: false,
    loaded: true,
    error: null 
  };
}

The state i'm using looks like this:

export interface TodoState {
  datas: {
    [todoId: string]: Todo
  }
  loading: boolean;
  loaded: boolean;
  error: any;
}

We use the reduce function here to transform the original source which is an array of object to entities ( a key which is an id associated to a todo object). I understand the reason why we use this function but i don't understand its inner code:

action.payload.reduce((accumulateur, iteration) => {
          accumulateur[iteration.id] = iteration; // <-- AS FAR AS I UNDERSTAND, ACCUMULATOR IS NOT AN ARRAY, HOW CAN WE ACHIEVE SUCH A THING
          return accumulateur;
        }, { ...state.datas })

Thank you in advance for helping me to put some light on this.

1 Answer 1

1

Imagine that

state.datas equals to:

{
  '0': {
    id: '0',
    message: 'Hello',
    done: false
  }
}

action.payload equals

[{
  id: '1',
  message: 'World',
  done: false
}]

After the reducer returns you will end up with

{
  '0': {
    id: '0',
    message: 'Hello',
    done: false
  },
  '1': {
    id: '1',
    message: 'World',
    done: false
  }
}

The important thing to note is that the id is a string. You can have an object with a key of '0'. It's no different than using any other string.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for helping, In the reducer, do we agree that the initial accumulateur value is { id: '0', message: 'work', done: false } ? This is not an array, why can we use this : accumulateur[iteration.id] = iteration;
The initial value is { '0': { id: '0', message: 'Hello', done: false } } . You can set properties values on objects like this: const x = {} x['0'] = 'hello'.
It helped me. Thank you !

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.