Search code examples
angularrxjsngrxeffect

Ngrx 8 - dispatch multiple else if conditions with multiple actions in effect


I am looking for the solution, for below situation:

 startMultpileActionDepensOnType$ = createEffect(() => this.actions$.pipe(
        ofType(startMultpileActionDepensOnType),
        withLatestFrom(this.store$.select(selectTypeActions)),
        map(([action, select]) => {
                const actionType = select.type.toLowerCase();

                if (actionType === ActionTypeEnum.TYPE_FIRST.toLowerCase()) {
                    return [getInitialDataStatus({statusType: 'disabled'}),
                        fetchImportantDataFirst()];
                } else if (actionType === ActionTypeEnum.TYPE_SECOND.toLowerCase()) {
                    return [getInitialDataStatus({}),
                        fetchImportantDataSecond());
                } else if (actionType === ActionTypeEnum.TYPE_THIRD.toLowerCase()] {
                    return [getInitialDataStatus({}),
                        fetchImportantDataThidr()];
                }
            }
        )
    ));

So: - I would like to run multiple action in array, - and using multiple else if case

I tried fixed it by dictionary... but maybe there is a much better solution.


Solution

  • Below is how you can use object to cut the if/else, in addition maybe something can also be improve with the enum compare here, it just seem a bit awkward

    const functionMap={
    [ActionTypeEnum.TYPE_FIRST.toLowerCase()]:[getInitialDataStatus({statusType: 'disabled'}),fetchImportantDataFirst()],
    [ActionTypeEnum.TYPE_SECOND.toLowerCase()]:[getInitialDataStatus({}),
                            fetchImportantDataSecond()],
    [ActionTypeEnum.TYPE_THIRD.toLowerCase()]:[getInitialDataStatus({}),
                            fetchImportantDataThidr()]
    }
    
     startMultpileActionDepensOnType$ = createEffect(() => this.actions$.pipe(
            ofType(startMultpileActionDepensOnType),
            withLatestFrom(this.store$.select(selectTypeActions)),
            map(([action, select]) => {
                    const actionType = select.type.toLowerCase();
                    return functionMap[actionType]
    
                }
            )
        ));