Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGXS State not changing

There might be someone who knows why NGXS state cannot change inside of HttpClient POST request.

ctx.patchState()

Only works outside HTTP POST request.

    @Action(SignIn)
    signin(ctx: StateContext<AppStateModel>, { payload }: SignIn) {

        // ctx.patchState({isLoggedIn:true}) this works!

        return this.api$.signin(payload)
            .pipe(
                tap((user: User) => {
                    console.log(user);
                    ctx.patchState({ isLoggedIn: true })

                })
            )
            .subscribe(
                (user: User) => {
                    ctx.patchState({ isLoggedIn: true })

                }
            )
    }
like image 268
Nacho Castillo Avatar asked Aug 26 '18 19:08

Nacho Castillo


People also ask

What is NGXS?

NGXS is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations. NGXS is modeled after the CQRS pattern - a pattern implemented in state management libraries such as NgRx and Redux.

What is patchState in angular?

The NGXS patchState method is used to do immutable object updates to the container state slice without the typical long-handed syntax. This is very neat and convenient because you do not have to use the getState and setState as well as the Object. assign(...) or the spread operator to update the state.


1 Answers

Actually, the state is changing, but you don't see it because you return subscription that hasn't been completed. In other words - You'll see the action being dispatched once the subscription of the returned observable completes.

As mentioned in the comments, the returned observable of the actions are being subscribed behind the scene, so there's no need to subscribe to it again.

After that being said, you can pass take(1) in the pipe.

What it does, it completes the subscription of the observable after it triggered once.

    @Action(SignIn)
    signin(ctx: StateContext<AppStateModel>, { payload }: SignIn) {
        return this.api$.signin(payload)
            .pipe(
                take(1), // <-- Add that
                tap((user: User) => ctx.patchState({ isLoggedIn: true }))
            );
    }
like image 85
Eliya Cohen Avatar answered Sep 30 '22 06:09

Eliya Cohen