I've been searching for the best approach to handle this situation, but I haven't come across one yet.
issue: I want to avoid duplicating action files, such as in the examples home-todos.actions and sport-todos-actions. Instead, I aim to use a single to-dos.action file and a common reducer.
example: Let's say I'm developing a todo application where dispatching an action with type 'ADD_TODO_ASYNC' triggers actions in both the home and sport sections.
todos.actions.ts
const ADD_TODO_ASYNC = 'ADD TODO ASYNC';
const ADD_TODO_COMPLETE = 'ADD TODO COMPLETE';
const ADD_TODO_FAILD = 'AD TODO FAILD';
class addTodoComplete {
type = ADD_TODO_COMPLETE;
}
class addTodoFaild {
type = ADD_TODO_COMPLETE;
}
export type Actions = addTodoComplete | addTodoFaild;
sport.effects.ts
@Injectable()
export class SportTodosService {
@Effect() ADD_TODO_ASYNC$ = this.actions$.ofType(TodosActionTypes.ADD_TODO_ASYNC)
.map(toPayload)
.swithMap( (todo: Todo) => this.api.addTodo(todo))
.map((todo: Todo) => TodosActionTypes.addTodoComplete(todo))
constructor(
private actions$: Actions,
private api: api
) { }
}
home.effects.ts
export class HomeTodosService {
@Effect() ADD_TODO_ASYNC$ = this.actions$.ofType(TodosActionTypes.ADD_TODO_ASYNC)
...
constructor(
...
) { }
}
reducer
function todosReducer(state, action: TodosActionTypes.Actions) {
switch (action.type) {
case TodosActionTypes.ADD_TODO_COMPLETE:
return state;
default:
return state;
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
StoreModule.forRoot({
sport: todosReducer,
home: todosReducer,
}),
EffectsModule.forRoot([
SportTodosService
HomeTodosService,
])
],
providers: [
api
],
bootstrap: [AppComponent]
})
export class AppModule { }
I'm trying to figure out the most optimal approach for this scenario. Should I prefix actions with context like 'HOME_ADD_TODO' & 'SPORT_ADD_TODO'?
Is there an official guideline to follow?
If you have a solution, whether it pertains to redux or ngrx, please share your insights.
Thank you!