Reputation: 121
In my project, when uid is saved in AsyncStorage, it means the user has already logged in.
Current code
Index.js
import React from 'react';
import Auth from 'app/src/common/Auth';
import { Text } from 'react-native';
export default class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
auth: true,
};
}
async componentDidMount() {
await this.setState({ auth: await Auth.user() });
}
render() {
const { auth } = this.state;
return (
{!auth ? (
<Text>You need to Log In!</Text>
) : (
<Text>You are Logged In!</Text>
)}
)
}
}
Auth.js
import { AsyncStorage } from 'react-native';
export default {
async user() {
let result = true;
const response = await AsyncStorage.getItem('uid');
if (!response) {
result = false;
}
return result;
},
};
This code is working but I would like to make this more simple like one function.
I would appreciate it if you could give me any advice.
Upvotes: 1
Views: 192
Reputation: 177
You can use promise and Do all Job in Index.js like
AsyncStorage.getItem('uid').then((uid) => {
this.setState({
auth : (uid) ? true : false
})
})
or simply use
const uid = await AsyncStorage.getItem('uid');
this.setState({ auth : (uid) ? true : false });
Upvotes: 1
Reputation: 8936
Are you going to be using that in more than one spot? why not just do it in your component?
async componentDidMount() {
const auth = await AsyncStorage.getItem('uid');
this.setState({ auth });
}
Upvotes: 0