LoginSignup
26
16

More than 5 years have passed since last update.

AsyncStorageを使ってみる

Last updated at Posted at 2018-10-23

ReactNativeでは簡単なデータならDBとか使わなくてもAsyncStorageを利用して保存できます。特に悩むことはありません。

基本的には、

  • 設定:AsyncStorage.setItem('key','value');
  • 取得:AsyncStorage.getItem('key');

とするだけ。

本家サイトを参考に下記のように記述してみました。

名前(name)を受け取り保存。nameをAlertで出力。

App.js
import React from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import { AsyncStorage } from "react-native"

export default class App extends React.Component {


  storeData = async (name) => {

    try{
      await AsyncStorage.setItem('name',name);
    }catch(error){
      console.log(error);
    }

    Alert.alert(name + ': stored');
  }

  getData = async () => {

    try{
      const value = await AsyncStorage.getItem('name');
      if(value !== null){
        Alert.alert('We have ' + value);
      }else{
        Alert.alert('We have no data');
      }
    }catch(error){
      console.log(error);
    }

  }

  render() {
    return (
      <View style={styles.container}>
        <Button
          title='保存'
          onPress={()=>this.storeData('Tanaka')}
        />
        <Button
          title='取得'
          onPress={()=>this.getData()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

26
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
16