简体   繁体   中英

What is the proper/right way to use Async Storage?

I am a react-native newbie.

I'm trying to use Async Storage in my application. I want the async storage to store token when user log in, it will navigate to homescreen. At homescreen, im trying to get the token through async storage and print it on console but all i get is promise. I just want to know what is the proper way to use Async storage especially in storing token? I know the alternative for this problem is using Redux state management, but I'm trying to learn the basic method.

I've tried to store the token in a variable in ComponentWillMount(), but it still does not work.

class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentWillMount() {
    token = getToken();
  }

  render() {
    const { navigate } = this.props.navigation;
    console.log(token);
    return (
      <View style={styles.container}>
        <Text> HomeScreen </Text>
      </View>
    );
  }
}

const getToken = async () => {
  let token = "";
  try {
    token = await AsyncStorage.getItem("token");
  } catch (error) {
    console.log(error);
  }
  return token;
};

First, I should note that componentWillMount is deprecated and you can use constructor or componentDidMount instead.

if you log token in getToken and after getting it, it will work fine. if you want to check if the user is logged in, you can do like this

constructor(props) {
    super(props);
    this.state = {};

    getToken().then((token)=>{
       console.log(token)
       //check if user is logged in
    })
}

or you can do this in componentDidMount . I hope this can help you

You should use it something like this,

import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native';

  //for storing Data

   setName = (value) => {
      AsyncStorage.setItem('name', value);
      this.setState({ 'name': value });
   }


//for Retrieving Data

 componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))

Here it is another simple example .

Try to use it with Async and await

setValue: function (key, value) {
    AsyncStorage.setItem(key, value)
},

getValue: async (key) => {
    let value = '';
    try {
        value = await AsyncStorage.getItem(key) || 'none';
    } catch (error) {
        // Error retrieving data
        console.log(error.message);
    }
    return value;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM