I'm using this package @react-native-async-storage/async-storage
package,
I have made a function to check whether a key exists, if so return true else return false.
Here is my code,
export const isAuthuenticated = async () => {
try {
const data = await AsyncStorage.getItem('@app_user');
if (data) return true;
} catch (e) {
return false;
}
};
console.log(isAuthuenticated())
When I try to console log this isAuthenticated()
method it gives me an object like this,
{"_h": 0, "_i": 0, "_j": null, "_k": null}
But I'm expecting to get true/false
as the returned value.
Update:
So I used .then()
statement since isAuthenticated()
function is asynchronous, but I receive an error saying Objects are not valid as a React child , This is my code,
import {isAuthenticated} from './src/middleware/middleware';
const App = async () => {
return (
<NavigationContainer>
{isAuthenticated().then(res => res && <AuthNavigator />)};
</NavigationContainer>
);
};
export default App;
CodePudding user response:
An async function always returns a promise. So what you need to do to get a boolean result is to either do
const res = await isAuthenticated();
console.log(res)
Or
isAuthenticated().then(res=>console.log(res))
If you want to use this in a component, you can simply store the value using an effect as such.
const App = () => {
const [flag,setFlag] = useState(false);
useEffect(()=>{
(
async()=>{
const x= await isAuthenticated();
setFlag(x);
})()},
[flag])
return (
<NavigationContainer>
{flag && <AuthNavigator />};
</NavigationContainer>
);
};
export default App;