Currently, I am immersed in a project that involves Angular 2 and @ngrx/store. I have a question regarding best practices and how to effectively execute certain actions.
In my development process, I have created a "web finder" tool for file management. This tool enables basic functionalities such as copying, moving files, etc.
Let me outline the steps involved in moving a file:
- Logic: Perform necessary verifications.
- Dispatch action A
- Dispatch action B
Initially, I had these 3 steps executed within my Angular component. However, upon reflection, I believe it would be more efficient to consolidate them into one action - performing verifications and then dispatching subsequent actions.
Why opt for this approach? Firstly, it significantly improves readability:
this._store.dispatch(copy(myFile));
as opposed to
// ...
// verifications
// ...
this._store.dispatch(action1(myFile, foo, bar));
this._store.dispatch(action2(myFile));
Furthermore, dispatching the 'copy' action on-the-fly eliminates any potential side-effects since verifications are handled within the action itself.
In essence, by centralizing logic within actions, components can remain simple and focus on their primary tasks (UI management).
Question 1: Is this considered good practice?
While I personally find this approach beneficial, I'm keen to hear about your experiences and insights.
Question 2: How should I proceed?
Implementing this methodology poses a challenge when dealing with action creators solely as functions without the ability to utilize decorators like 'Injectable' or inject instances using 'constructor.'
Here's an example of action creators:
import { Action } from '@ngrx/store'
export const NAVIGATE_TO_NODE:string = '[Browser] Navigate to node';
<!-- Additional action constants omitted for brevity -->
export const navigateToNode:(nodeId: number, paneId?: number)=>Action = (nodeId: number, paneId?: number) => {
return {
payload: { nodeId, paneId },
type: NAVIGATE_TO_NODE
};
};
<!-- Additional action creators omitted for brevity -->
To address this issue, having prior experience with Redux in React projects, I discovered a useful library called redux-thunk which facilitates dispatching actions directly from action creators.