LoginSignup
0
0

More than 3 years have passed since last update.

【NGXS】ネストした状態の部分更新を簡潔に書く(patch state operator)

Posted at

下記のような型の状態を管理するNGXSのStateを考える。

export interface PersonStateModel {
  name: {
    firstName: string;
    lastName: string;
  };
  age: number;
}

firstNameだけ更新するコードを書こうとすると、ネストが2階層なのでctx.patchStateでは意外とシュッと書けない


export class UpdatePersonFirstName {
  static readonly type = 'Update person';
  constructor(public payload: string) {}
}

@State<PersonStateModel>({
  name: 'person',
  defaults: {
    name: {
      firstName: 'Taro',
      lastName: 'Yamada',
    },
    age: 20;
  }
})
@Injectable()
export class PersonState {
  @Action(UpdatePersonFirstName)
  updatePersonFirstName(ctx: StateContext<PersonStateModel>, { payload }: UpdatePersonFirstName) {
    ctx.patchState({
      name: {
        ...ctx.getState().name,   // ここがなんとかできないか?
        firstName: payload
      }
    });
  }

State Operatorの「patch」を使うと…

@Injectable()
export class PersonState {
  @Action(UpdatePersonFirstName)
  updatePersonFirstName(ctx: StateContext<PersonStateModel>, { payload }: UpdatePersonFirstName) {
    ctx.setState(
      patch({
        name: patch({
          firstName: payload
        })
      })
    });
  }

ネストさせられるので、name.firstNameだけ更新されるという意図が明確になって良いのではないかと思います。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0