Where should I put business logic designed to convert data intended for the ngrx store: into effects or reducers?

My question is related to ngrx effects and gears .

I need to convert the data extracted from the backend before putting it in the ngrx repository. The data received from the backend is a simple Message array ( Message is a custom type in my application):

 Message[] 

I need to convert an array to the following:

 Map<string, Message[]> 

Basically, I group user messages by the identifier (recipient or sender) of the counterparty (key).

I'm not sure where to convert from Message[] to Map<string, Message[]> : should I turn the conversion business logic into @Effect or into a reducer function?

+7
redux ngrx ngrx-effects
source share
3 answers

The conversion can go either to the effect or to the gearbox.

If there was any check that was supposed to be done, I would put it into action - where I would have the opportunity to send an error message.

Otherwise, I would put it in the reducer, since where I usually converted the action payload to state.

There is another option: you can use the selector. That is, messages can be stored in state as a simple array, and the selector can be used to convert status messages, group them by counterparty - or something else. If I had several ways to group messages, this is the option I would choose.

@ngrx/example-app contains several sample selectors :

 /** * A selector function is a map function factory. We pass it parameters and it * returns a function that maps from the larger state tree into a smaller * piece of state. This selector simply selects the `books` state. * * Selectors are used with the `select` operator. * * ```ts * class MyComponent { * constructor(state$: Observable<State>) { * this.booksState$ = state$.select(getBooksState); * } * } * ``` */ export const getBooksState = (state: State) => state.books 
+4
source share

The way I do this is fetching and converting data into a service, like in the old days.

Effects respond to an action and make a call through the service to return data and send other actions based on the responses received.

This greatly simplifies testing, since the service is stored separately from the effect, the main purpose of which is to respond to a specific action, and not to data packaging.

The gearbox can be used for this, but again you have to keep it clean for easy reading.

+3
source share

My opinion:

  • Data received from the backend will be stored in the storage unchanged.

  • Using selectors as business logic (combining, transforming, etc.) for silent components.

  • Perhaps the only conversion is to use normalizr to align the data.

0
source share

All Articles