platform icon indicating copy to clipboard operation
platform copied to clipboard

Reproduce state for each list item

Open argygkou opened this issue 8 years ago • 4 comments

Hi, can someone provide an example to me how can I reproduce a reducer's state to each list item, so I can handle the state of each list item separately.. After an extensive search, I didn't manage to find an example and I started considering if it is a bad architecture for redux/ngrx to have a state for each list item.

argygkou avatar Oct 01 '18 13:10 argygkou

I'm not sure what you mean exactly, could you show some code?

If you want to modify a list item you can:

  • iterate over the list items and update the one(s) that have to be updated:
return entities.map(e = {
   if(e.id === payload.id) {
     return {...e, completed: true};
   }
   return e;
});
  • if you work with a normalized state this becomes easier with:
return {
  ...entities,
  [payload.id]: {
    ...entities[payload.id],
    completed: true
  }
}
  • create an itemReducer and invoke it from the listReducer or create a meta-reducer:
   return entities.map(entity => itemReducer(entity, payload));

timdeschryver avatar Oct 02 '18 12:10 timdeschryver

Let's say we have a list of items:

export interface State {
  items: any[]
  loading: boolean
}

and for each item in the list I want to have a second state which is something like this:

export interface State {
like: boolean;
comments: any[];
}

so for every item in the list, I want to dispatch an action for getting the like boolean and another action for getting the list of comments.

I tried it that but all items had the same values and it was the values from the last item that dispatched the actions. Am I missing something architecturaly or something else?

argygkou avatar Oct 02 '18 14:10 argygkou

I thought you wanted to update the set, but you want to read from the state? I think talking in the gitter channel will be more productive.

timdeschryver avatar Oct 02 '18 14:10 timdeschryver

I have the same issue. Can you please also provide the answer in here?

bogdandevlpr avatar Dec 17 '18 14:12 bogdandevlpr