로메오의 블로그

[React Native] async-storage 본문

Frontend/React

[React Native] async-storage

romeoh 2022. 11. 18. 14:01
반응형

React 목록

 

async-storage 설치

$ npm install @react-native-async-storage/async-storage

 

 

 

App.tsx

import React, {useEffect, useState} from 'react';
import {
  View,
  SafeAreaView,
  StatusBar,
  Text,
  TouchableOpacity,
  StyleSheet,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

type Nation = {
  nation: string;
  company: string;
};

const App = () => {
  const [list, setList] = useState<Nation[]>([]);
  const key = 'com.key';

  useEffect(() => {
    AsyncStorage.setItem(key, JSON.stringify(list));
  }, [list]);

  const saveData: Nation = {
    nation: 'korea',
    company: 'samsung',
  };

  const saveStorage = () => {
    setList([...list, saveData]);
  };

  const patchStorage = async () => {
    const data = await AsyncStorage.getItem(key);
    console.log(data);
    if (data) {
      setList(JSON.parse(data));
    }
  };
  const resetStorage = () => {
    AsyncStorage.removeItem(key);
    setList([]);
  };
  return (
    <SafeAreaView>
      <StatusBar barStyle="dark-content" />
      <TouchableOpacity
        onPress={() => {
          saveStorage();
        }}>
        <Text style={styles.button}>저장</Text>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() => {
          patchStorage();
        }}>
        <Text style={styles.button}>불러오기</Text>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() => {
          resetStorage();
        }}>
        <Text style={styles.button}>리셋</Text>
      </TouchableOpacity>

      {list.map((nation, index) => {
        return (
          <View key={index}>
            <Text>{nation.nation}</Text>
          </View>
        );
      })}
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  button: {
    fontSize: 20,
    padding: 10,
  },
});

 

 

 

 

React 목록

반응형
Comments