jermylucas / velo-coach-app

application for workouts
0 stars 0 forks source link

On login/signup, initial SetUser() state call results in error #25

Closed jermylucas closed 3 years ago

jermylucas commented 3 years ago

My login function:


login(email: string, password: string) {
  return this.fireAuth
    .signInWithEmailAndPassword(email, password)
    .then((res: any) => {
      console.log('LOGIN RES', res);
      this.store.dispatch(new SetUser(res.user as any));

      // Set item to storage for autologin fn
      this.localStorage.setItemLocally('userData', JSON.stringify(res.user));
    });
}

Everything works as expected, however, the ...dispatch(new SetUser(res.user as any)) results in the following error:

core.js:6456 ERROR TypeError: Cannot read property 'user' of undefined
    at UserState.setUser (user.state.ts:101)
    at StateFactory.invokeActions (ngxs-store.js:2607)
    at MergeMapSubscriber.project (ngxs-store.js:2573)
    at MergeMapSubscriber._tryNext (mergeMap.js:44)
    at MergeMapSubscriber._next (mergeMap.js:34)
    at MergeMapSubscriber.next (Subscriber.js:49)
    at FilterSubscriber._next (filter.js:33)
    at FilterSubscriber.next (Subscriber.js:49)
    at InternalActions.next (Subject.js:39)
    at InternalActions.next (ngxs-store.js:1422)

My action:

@Action(SetUser)
setUser(ctx: StateContext<UserStateModel>, { payload }: any) {
  console.log('SET USER PAYLOAD', payload);
  ctx.setState(
    patch<UserStateModel>({
      user: {
        email: payload.email,
        uid: payload.uid,
        displayName: payload.displayName,
      },
    })
  );
}

So it seems like something is going wrong on the patch<... within this action. The payload looks as such:

{
    "uid": "hzMX0YufPyRPLaqqiL7k1",
    "displayName": "First Last"
    "email": "first@last.com",
}

and has a few other things like tokens and whatnot. What's odd, is that I have an autologin function that takes the object from localStorage, parses it, and does the same action. But this doesn't return any error...

  autoLogin() {
    const userData = JSON.parse(this.localStorage.getItemLocally('userData') as any);
    if (userData == null) {
      return;
    }
    const loadedUser: User = {
      email: userData.email,
      uid: userData.uid,
      displayName: userData.displayName,
    };
    this.store.dispatch(new SetUser(loadedUser as any));
  }

This properly sets everything to my store. So once I log in, I get an error and have no stored User in my state. However, once I refresh the page, since I have the data in my storage, everything works

jermylucas commented 3 years ago

Closed as per PR #26