How do I dispatch multiple actions in react-native using hooks?

☆樱花仙子☆ 提交于 2021-01-29 07:51:51

问题


From the code below, I am trying to dispatch two actions that take the registered name and surname of a logged in user from the firestore database user collection and updates the name and surname state in my app. However, for some reason, only the second action gets dispatched. The surname state in my app gets updated but the name state remains empty.

I've tried using an async function to call the dispatch but still nothing. I've tried moving the dispatch code to different sections of the code and still nothing. No matter where I put the code, only the second dispatch gets called. Nothing seems to be working so far. I can't seem to make two dispatches work only one. As a side note, I am not using redux, or any middleware just react hooks with useReducer and useContext.

firebase.auth().onAuthStateChanged(user => {
    if (user) {
        const userId = user.uid;
        const db = 
firebase.firestore().collection('users').doc(userId);
        db.get()
        .then(userId => {
            if (userId) {
                dispatch({
                    type: 'fill_name',
                    payload: userId.data().Name
                })
                dispatch({
                    type: 'fill_surname',
                    payload: userId.data().Surname
                })
            } else {
                return null;
            }
        })
    } else {
        navigate('Intro');
    }
});

回答1:


the reason why you cant dispatch twice from one action is for the main reason why { dispatch } logic created for the first place. for having one place with all the "app-truth" in it, with one way of change the Torah and one mountain to get one

what you can do is dispatch both first and last name like -


firebase.auth().onAuthStateChanged(user => {
    if (user) {
        const userId = user.uid;
        const db = 
firebase.firestore().collection('users').doc(userId);
        db.get()
         .then(userId => {
            if (userId) {
                dispatch({
                    type: 'fill_name',
                    firstName: userId.data().Name
                    surName: userId.data().Surname
                })
            } else {
                return null;
            }
        })
    } else {
        navigate('Intro');
    }
});

and when listening in the reducer to the action it gonna look like -

   action.firstName

for first name



来源:https://stackoverflow.com/questions/58341848/how-do-i-dispatch-multiple-actions-in-react-native-using-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!