Reputation: 537
I need to push a new route after a user uploads an image. The new route is different depending on the specific module the user is currently in. At the moment, the actionRouteEpic filters the new route and then calls PUSH_ROUTE
within each if statement, however is there a way of updating a route
variable and then calling PUSH_ROUTE
once at the end of the switch map?
The first code example is the working but clunky looking version. The second example is the latest unsuccessful attempt at a cleaner version.
Currently this works:
const actionRouteEpic = action$ =>
action$.pipe(
ofType('DISPATCH_ACTION_ROUTE'),
switchMap(action => {
if (action.module === 'module_one') {
return of({
type: 'PUSH_ROUTE',
route: '/route-one'
});
}
if (action.module === 'module_two') {
return of({
type: 'PUSH_ROUTE',
route: '/route-two'
});
}
if (action.module === 'module_three') {
return of({
type: 'PUSH_ROUTE',
route: '/route-three'
});
}
return empty();
}
);
const pushRouteEpic = action$ =>
action$.pipe(
ofType('PUSH_ROUTE'),
map(action => push(`${action.route}`))
);
Attempt at cleaner version:
const actionRouteEpic = action$ =>
action$.pipe(
ofType('DISPATCH_ACTION_ROUTE'),
switchMap(action => {
let route = ''
if (action.module === 'module_one') {
route = '/route-one';
}
if (action.module === 'module_two') {
route = '/route-two';
}
if (action.module === 'module_three') {
route = '/route-three';
}
return of({
type: 'PUSH_ROUTE',
route: route
});
}
);
const pushRouteEpic = action$ =>
action$.pipe(
ofType('PUSH_ROUTE'),
map(action => push(`${action.route}`))
);
Thanks, appreciated.
Upvotes: 1
Views: 108
Reputation: 8686
There is nothing wrong with your code, but you can make it "cleaner" by using a function acting on a map instead :
const selectRouteFromActionModule = action =>
of(
{
module_one: '/route-one',
module_two: '/route-two',
module_three: '/route-three',
}[action.module],
);
const actionRouteEpic = action$ =>
action$.pipe(
ofType('DISPATCH_ACTION_ROUTE'),
switchMap(selectRouteFromActionModule),
);
Upvotes: 1
Reputation: 6924
Use js object as hash map and define a "router" which maps every module to relevant entry path
const actionRouteEpic = action$ =>
const router = {
module_one: '/route-one',
module_two: '/route-two'
}
action$.pipe(
ofType('DISPATCH_ACTION_ROUTE'),
switchMap(action => {
return of({
type: 'PUSH_ROUTE',
route: router[action.module]
});
}
);
Upvotes: 1
Reputation: 9988
const actionRouteEpic = action$ =>
action$.pipe(
ofType('DISPATCH_ACTION_ROUTE'),
switchMap(action => of({
type: 'PUSH_ROUTE',
route: action.module === 'module_one' ? '/route-one' :
action.module === 'module_two' ? '/route-two' :
'/route-three'
})
);
Upvotes: 1