「基礎から学ぶReact Native入門」の感想・備忘録3

3つの方法がある。

  1. AsyncStorage
  2. SQLite
  3. サーバに保存

AsyncStorage

インストール

expo install @react-native-async-storage/async-storage

インポート

import AsyncStorage from '@react-native-async-storage/async-storage'

保存

await AsyncStorage.setItem("1", JSON.stringify({id: 1,body: "text"}))

取得

await AsyncStorage.getItem("1");

全件取得

const keys = await AsyncStorage.getAllKeys()
const list = await AsyncStorage.multiGet(keys)
const jsons = list.map(keyValue=>JSON.parse(keyValue[1]))

メモアプリの作成

import { FlatList, StyleSheet, View } from 'react-native'
import { Button, FAB, List } from 'react-native-paper'
import { useEffect, useState } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage'

export default function Main({navigation}) {
  const [memos, setMemos] = useState([])
  useEffect(() => {
    const initialize = async () => {
      const keys = await AsyncStorage.getAllKeys()
      const list = await AsyncStorage.multiGet(keys)
      setMemos(list.map(json=>JSON.parse(json[1])))
    }
    return navigation.addListener("focus", initialize);
  })
  return (
    <View style={styles.container}>
      <FlatList data={memos} keyExtractor={item=>item.id} renderItem={({item})=>(
        <List.Item title={item.body} description={`作成日:${item.created}`} descriptionStyle={{textAlign: "right", width: 300}}/>
      )}/>
      <Button mode="contained" onPress={()=>{AsyncStorage.clear();setMemos([])}}>全削除</Button>
      <FAB icon="plus" style={{position: "absolute", right: 16, bottom: 16}} onPress={()=>navigation.navigate("Compose")}/>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
import { StyleSheet, View } from 'react-native'
import { Button, FAB, TextInput } from 'react-native-paper'
import { useState } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage'

export default function Compose ({ navigation }) {
  const [text, setText] = useState('')
  const save =  async () => {
    const now = (new Date()).toLocaleString();
    await AsyncStorage.setItem(now, JSON.stringify({id: Math.random()*10000000,body: text, created: now}))
    navigation.navigate('Main')
  }
  return (
    <View style={styles.container}>
      <TextInput mode="outlined" value={text} placeholder="メモを入力してください" multiline={true} style={{marginVertical: 20}} onChangeText={(val)=>setText(val)}/>
      <Button mode="contained" onPress={save}>保存</Button>
      <FAB
      icon="arrow-left"
      style={{
        position: 'absolute',
        right: 16,
        bottom: 16,
      }}
      onPress={() => navigation.navigate('Main')}
    />
    </View>
  )
}

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

コメント

タイトルとURLをコピーしました