1

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.

2 Answers 2

1

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  });
Sign up to request clarification or add additional context in comments.

Comments

0

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 });
  }

3 Comments

Yes, I'm going to use this in more than one spot.
are you using any global state management like redux? because then you can fetch it once here and grab the value from redux in any other component you need it
I'm not using redux. Thanks, looks like there are better ways than my current one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.