Search code examples
ngrx

createAction ngrx methodology


I've investigated quite a few different createAction methods and I'm confused on which one to use.

Let's say I have a username and password for login I've seen the following ways scattered across the internet:

export const myAction = createAction(
    '...',
    props<{ payload: { username: string, password: string }}>
);

vs

export const myAction = createAction(
    '...',
    props<{ username: string, password: string }>
);

I find the second one much cleaner because I could potentially have this:

export const myAction = createAction(
    '...',
    props<userModel>
);

The problem is when I log out the action the type is one of the properties in the second example which means I may run into conflicts if the userModel contains a type property. On the other side the first example would mean I'd have the word payload sprinkled all over my application which seems excessive.

Example in stackoverflow of the second example:

How do you detect NgRx createAction duplicate types


Solution

  • The problem is when I log out the action the type is one of the properties in the second example which means I may run into conflicts if the userModel contains a type property

    NgRx will warn you if this happens, this will throw an error and you won't be able to compile. The payload property is a pattern used before the createAction was introduced, that's why you will see a lot of examples with a payload property.