Search code examples
ngxs

ngxs labs immer asking for full state?


I had strictly followed ngxs/labs immer documentation to adapt my code and find this strange behavior.

Why should setState ask for all state properties in:

  export class DadesStateModel {
    apartats: IApartat[];
    authors: IAuthor[];
  }  
  (...)
  @Action(SetArticles)
  @ImmutableContext()
  setArticles({setState}: StateContext<DadesStateModel>, {apartat}: SetArticles) {
    setState((state: DadesStateModel) => ({
      state.apartats[state.apartats.findIndex(ap=>ap.Id===apartat.Id)] = apartat;
      return state;
    }))
  }

with the following error message:

Argument of type '(state: DadesStateModel) => { state: DadesStateModel; (Missing): IApartat; return: DadesStateModel; }' is not assignable to parameter of type 'DadesStateModel | StateOperator<DadesStateModel>'.
  Type '(state: DadesStateModel) => { state: DadesStateModel; (Missing): IApartat; return: DadesStateModel; }' is not assignable to type 'StateOperator<DadesStateModel>'.
    Type '{ state: DadesStateModel; (Missing): IApartat; return: DadesStateModel; }' is missing the following properties from type 'DadesStateModel': authors.

Solution

  • Even though my answer comes a bit late: You are seeing this error due to a syntactical mistake. You are wrapping the enclosing {} in your lambda with brackets ({}), so it assumes that what you intended to be the body of the lambda to be the return value of the lambda. Just remove the enclosing brackets and it works.

    setState((state: DadesStateModel) => { // Instead of "({"
      state.apartats[state.apartats.findIndex(ap=>ap.Id===apartat.Id)] = apartat;
      return state;
    }); // Instead of "}));"