Sachin Kumar
Sachin Kumar

Reputation: 3240

Equivalent to getState() method of react-redux in ngrx | Angular 6 | ngrx 6

I have created an application using react and redux. In which I used getState() to get the state of the store and fetch the particular slice by destruction like this.

const { user } = getState();

Now I want to move to the application in angular 6. I installed ngrx v6.0. I read the documentation but I didn't find the method of getting the user slice. However, I think I can achieve the thing by creating a selector like this

export const selectUser = (state: AppState) => state.user;

But I need to subscribe that selector and get the user state like this.

this.store.pipe(select(fromRoot.selectUser)).subscribe(
        user => this.user = user
    )

Do I need to create a manual function like below?

function getState(store: Store<State>): State {
    let state: State;

    store.take(1).subscribe(s => state = s);

    return state;
} 

Can someone provide the best solution for this or I miss something?

I am also facing another problem with creating a selector. I dispatch an action with payload userData(which one is coming from API response) AppComponent@ngOnInit() this.store.dispatch(new LoadUserAction(this.userData));

But when I use the user selector for getting user slice of state in the feature module's component HomeComponent@ngOnInit()

this.store.pipe(select(fromRoot.selectUser)).subscribe(
            user => this.user = user //user is same as intial not the updated one.

        )

I didn't get the data at once. Always return the initial state.

Do I need to use effects or placing some if conditions?

Can someone explain to me how to perform another action after getting the correct data from the first selector?

Upvotes: 0

Views: 987

Answers (1)

Jo&#227;o Ghignatti
Jo&#227;o Ghignatti

Reputation: 2401

Yes, NgRx has no instant get() method to access a slice of your store. I couldn't find it, but there's an issue on GitHub where they said that on the first version they had it, but people weren't using it correctly, so they removed and now you only get Observables.

Your

this.store.pipe(select(fromRoot.selectUser)).subscribe(
  user => this.user = user
)

is correct. You just gotta remember to unsubscribe from it.

If you can, there's no problem on storing the whole Observable, without having to subscribe on it. Angular has a async pipe so you can easily use Observables on your templates and you can always operate over that Observable and return a new Observable to your required needs.

Ps: It's best to use createSelector method.

export const selectUser = createSelector(
  selectAppState,
  (state: AppState) => state.user;
);

Upvotes: 1

Related Questions