angularangular6ngxsangular-state-managmement

Appending Data to State in Angular NGXS


I have a problem on how will be i able to append new datas since I'm making a server side scrolling. The posts is removing the old data when the new data arrives BUT i just want the new data to append and not not delete the old data in posts

TS

  page = 1;

    constructor(private store: Store) {
        this.store.dispatch(new GetPostsPerPage('', this.page.toString()));
    }

     onScroll() {
        this.store.dispatch(new GetPostsPerPage('', (this.page += 1).toString()));
      }

State

@Action(GetPostsPerPage)
      getPostsPerPage(ctx: StateContext<PostStateModel>, { key, pageNumber }: GetPostsPerPage) {
        return this.postsService.getPostsPerPage(key, pageNumber).pipe(
          tap((result: Post[]) => {
            console.log(result);
            ctx.patchState({
              posts: result['data'],
            });
          }),
          catchError(err => {
            console.log(err);
            return throwError(err);
          })
        );
      }

Solution

  • When you patch state, you need to append the results to the current state value, rather than overriding it with posts: result['data'].

    In your tap operator, you could use a spread to append the new posts:

    var currentPosts = ctx.getState().posts;
    ctx.patchState({
     posts: [...currentPosts, ...result['data']]
    });
    

    NGXS also has some (relatively new) built-in State Operators that make handling these scenarios easier, see the documentation specifically the append operator.