0

im a new to react native but trying to build my own application. I'm trying to pass storeKey and userName obtained from DB to CustomDrawer and Drawer.Screen so I don't need to repeat the function everytime. so, it's working inside HomeScreen, console.log prints proper value. However, when I pass it in Drawer.Screen 'stock', and then print it in that module, it shows empty array.
How can I pass value from async to drawer navigator properly? and how can I pass it to CustomDrawer? will {...props} already contain the value? When I print props.params in the CustomDrawer module, it only says undefined..

const HomeScreen = ({ navigation }) => {

const [storeKey, setStoreKey] = useState([]);
const [userName, setName] = useState([]);
useEffect(async() => {
    let isMounted = true;
    if(isMounted){
        console.log('zzzz')
        const auth = getAuth();
        const user = auth.currentUser;
        if(user !== null){
            const email = user.email;
            const UserInfo = await getDoc(doc(db, 'users', email));
            if(UserInfo.exists()){
                setName(UserInfo.data().name);
                setStoreKey(UserInfo.data().storeKey)
                return () => {
                    isMounted = false
                }
            }
            else{
                console.log('None')
            }
    }
}
}, [storeKey]);

console.log('this',storeKey)

return (
    <Drawer.Navigator drawerContent={props => <CustomDrawer {...props} />} screenOptions={headerStyles} initialRouteName={HomeScreen} >
        <Drawer.Screen name='Search' component={SearchScreen} options={QuitIcon}/>
        <Drawer.Screen name='Stock' component={StockScreen} options={QuitIcon} initialParams={{storeKey: storeKey}}/>
    </Drawer.Navigator>
)

}

maz32
  • 127
  • 1
  • 13

1 Answers1

0

Even if the UseEffect is async or none the following code will be the same,

when calling the console.log('this', storeKey) the data is not yet in the state, to wait the useEffect run before continue the code, you have to add an empty array as a second argument in the useEffect function like this :

useEffect(() => {
  
}, []) // <-- empty array here

by this way your useEffect will be run only the first render of the app and the program will wait the useEffect to be run before continue.

Wawa
  • 273
  • 2
  • 11
  • see https://stackoverflow.com/questions/58579426/in-useeffect-whats-the-difference-between-providing-no-dependency-array-and-an for more details – Wawa Dec 23 '21 at 01:31