0

I have an array of TripEvents in my store:

export interface TripEvent {
    id: string;
    title: string;
    address: string;
    image: string;
    prevSibling: {
        title: string,
    };
}

I also have an effect triggered whenever an item is added to an array in my store:

findSiblings$ = createEffect(() => this.actions$.pipe(
    ofType(TripsActionTypes.AddEvent),
    concatMap(() => this.tripsService.findSiblings().pipe(
        map(events => SiblingsFound(events))
    ))
));

The findSiblings() function needs to do some complicated work eventually so I have put it in a service, but for now I'm just trying to update each event in the array with the name of its sibling:

findSiblings() {
  this.store.select(getEvents).pipe(take(1)).subscribe(events => {
    this.events = events;
  });

  const updatedEvents = this.events.map((currentEvent, index, array) => {
    if (index > 0) {
      const prevEvent = array[index - 1];
      currentEvent.prevSibling.title = prevEvent.title;
    }
    return currentEvent;
  });

  return of(updatedEvents);
}

This gives me the error TypeError: Cannot assign to read only property 'title' of object '[object Object]'. I understand maybe this is because I am trying to update items in the store directly? But no matter how I try to clone or copy the array or elements I get the same error, so what is the general approach to a) updating the store via a service, or b) returned modified items from the store for the action/reducer to update (e.g. via SiblingsFound action above).

DaveO
  • 1,909
  • 4
  • 33
  • 63
  • 1
    You should update the store data in reducer only. Are you not using the reducer? – user2216584 Sep 08 '19 at 04:00
  • I'm not trying to update the store directly, I'm trying to get an array of objects from the store (as a clone) update properties on them and return them to the effect which passes them onto the SiblingsFound action for the reducer to update the store. Based on https://stackoverflow.com/a/46794068/422611 it appears I can't clone the objects from the store to do any work as clones end up read-only as well, so I found ```this.events = JSON.parse(JSON.stringify(events));``` on line 3 of `findSiblings()` is the only thing that works, but I'm sure there's a better way. – DaveO Sep 08 '19 at 04:32
  • You must do deep cloning either manually or use a lodash library. – user2216584 Sep 08 '19 at 05:46
  • 2
    Dont try to break redux pattern. Just update your store using reducer – Tony Ngo Sep 08 '19 at 12:05
  • I don't believe I'm breaking the pattern. I just want to get some objects from the store, do some work on them (without UI) and save them back, I'm looking for the recommended way to do that. – DaveO Sep 10 '19 at 04:18

0 Answers0