Can I pass parameter other than Payload to NGXS action?

42 Views Asked by At

I am trying to have a Ngxs action that takes a parameter along with Payload. I use this parameter to decide if I need to send a notification or not.

@Action(UpdateUser)
  async UpdateUser(
    ctx: StateContext<ProfileStateModel>,
    userProfile: User,
    notify: boolean
  ): Promise<void> {
      await this.updateProfileSvc(userProfile){
         .subscribe({
             next: (data: User) => {
                 ctx.setState({...state, sendNotification: notify});
              }
           })
     }
 }

User is the payload in this Action. When I pass the second parameter "notify" with value "true/false", I always receive it as undefined.

How to have a parameter other than payload in the Ngxs action?

I tried to print the value of notify in the console, and I see it "undefined" always.

Please share your inputs here/ Thanks.

1

There are 1 best solutions below

0
adamskey On

It is possible to pass any data to the constructor of action object itself and then use that action object inside your action handler. For example:

export class UpdateUser {
  public static type: string = '[Users] Update user';

  constructor(public readonly user: UserModel, public readonly notify: boolean) {}
}

Then your action handler will simply take the action instance as a method parameter:

@Action(UpdateUser)
updateUser(ctx: StateContext<Users>, action: UpdateUser) {
  const userToUpdate: UserModel = action.user;
  const shouldNotify: boolean = action.notify;
  //...///
}

Relevant documentation: Actions with a payload