Search code examples
firebasereact-nativemobxmobx-state-tree

Trying to create firebase user in MST(mobx state tree)action


I am trying to create new user in firebase using MST actions.

My code looks something like this:

.actions((self => ({
    createUserWithEmailPassword:
        flow(function*(password: string) {
            console.log('creating user');
            yield firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
            console.log('set Persistence');
            const user = yield firebase.auth().createUserWithEmailAndPassword(self.email, password);
            console.log('CREATED USER', user);
            self.uid = user.uid;
        })
}));

It does create a user, but it won't go ahead of createUserWithEmailAndPassword call. (i.e. it will never console 'CREATED USER`)

I also have onPatch console on user, but it also won't show user updating.

I tired to console fake api call

let res = yield fetch("https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole")

this works perfectly.

Looks like there is something wrong with createUserWithEmailAndPassword but I can't figure it out.


Solution

  • Your code should work but you can try this as well

    createUserWithEmailPassword(password: string) {   
      flow(function*() {
                console.log('creating user');
                yield firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
                console.log('set Persistence');
                const user = yield firebase.auth().createUserWithEmailAndPassword(self.email, password);
                console.log('CREATED USER', user);
                self.uid = user.uid;
            })() // <--- check this
    }
    

    Flow will return a function that you need to call

    OR like this

    createUserWithEmailPassword(password: string) {
            const run = flow(function*() {
                console.log('creating user');
                yield firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
                console.log('set Persistence');
                const user = yield firebase.auth().createUserWithEmailAndPassword(self.email, password);
                console.log('CREATED USER', user);
                self.uid = user.uid;
            })
    
            run()
    }