Search code examples
ngrxngrx-storengrx-effects

Where should I call functions with side effects like Date.now or random?


For example I need a current date or shuffle a list in reducer. Should I use effects for that?

 @Effect()
  foo$: Observable<Action> = this.actions$.pipe(
    ofType('Foo'),
    map(action => {
      //create result with Date.now or shuffle
      return {type: 'Foo_Result', payload: result}
    }

    )
  );

It feels like overkill. What is the best practice?


Solution

  • I think the answer is already provided in the comments but for the completeness let me provide a "real" answer here.

    Like @cartant said, you can put these side effects inside an action creator. These action creators don't have to be pure, meaning you could so something like:

    const addTodo = ({
        id = uuid(),
        description = '',
        createDate = Date.now
      } = {}) => ({
        type: 'ADD TODO',
        payload: { id, description, createDate }
      })
    

    Doing this has an extra benefit, which is easier tests:

    • In your action test, you test if the id and createDate is there but you dont test the values
    • To test your reducer you can set these values, addChat({id: 4654, description: 'a random todo', createDate: 111}).

    These are the reasons why I'm more in favor of doing this inside an action creator, you could do it inside an effect if you like but just don't do it inside the reducer functions.

    A reducer function must remain pure.

    For more info, I refer you to Let’s have a chat about Actions and Action Creators within NgRx