I have this menu where I filter the button when user is logged and I'm accessing a function from a separate file to check out if user is logged or not.
From menu
import { IsLogged } from '../GlobalFunctions';
const SubDrawer1 = ({ data, onChange }) => (
<View>
{
IsLogged() ? (
<View>
<TouchableOpacity onPress={()=>{onChange('LogoutScreen')}}>
<Text>Logout</Text>
</TouchableOpacity>
</View>
) : (<View />)
}
</View>
);
export default SubDrawer1;
From GlobalFunctions
export function IsLogged(){
AsyncStorage.getItem('userId').then((userId) => {
return userId ? true : false
})
}
From menu I call out IsLogged()
function but the value is undefined
when I console.log it. It supposed to return either true
or false
.
because AsyncStorage will take some time, and before that function completes its execution. (Because everything in JS is asynchronous)
So just make it wait until it finishes getting an item,
export function async IsLogged(){
let userId = await AsyncStorage.getItem('userId');
return userId ? true : false
}
You are trying to call a async function, so you need to add some extra code. Try the following.
SubDrawer1
import { Text, View, TouchableOpacity } from "react-native";
import React, { Component } from "react";
import { IsLogged } from "../GlobalFunctions";
const SubDrawer1 = async ({ data, onChange }) => {
const status = await IsLogged();
if (status === true) {
return (
<View>
<View>
<TouchableOpacity
onPress={() => {
onChange("LogoutScreen");
}}
>
<Text>Logout</Text>
</TouchableOpacity>
</View>
</View>
);
} else {
return (
<View>
<View />
</View>
);
}
};
export default SubDrawer1;
'IsLogged()' Global function
export function async IsLogged(){
let userId = await AsyncStorage.getItem('userId');
return userId ? true : false
}
'SubDrawer1' using class
...
import SubDrawer1 from "./SubDrawer1"; // import your 'SubDrawer1' component
var subDrawer1Component; // declare a variable for your rendering component
//Your main class
export default class ClassName extends Component<Props> {
componentDidMount() {
this.getComponentInfo(); //Call this method to get function
}
getComponentInfo = async () => {
subDrawer1Component = await SubDrawer1();// Will take the component
this.setState({ isDataGet: true });
};
render() {
return (
...
{subDrawer1Component}
...
);
}
}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.