Ayncstorage

김수민·2023년 8월 30일
0

React-Native

목록 보기
5/8

디바이스에 데이터 저장하여 사용하는 Ayncstorage

설치

https://react-native-async-storage.github.io/async-storage/docs/install
npm install @react-native-async-storage/async-storage

사용

데이터 저장

[문자열의 경우]

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('my-key', value);
  } catch (e) {
    // saving error
  }
};

[Object의 경우]

import { AsyncStorage } from '@react-native-async-storage/async-storage';

const storeData = async (value) => {
  try {
    const jsonValue = JSON.stringify(value);
    await AsyncStorage.setItem('my-key', jsonValue);
  } catch (e) {
    // saving error
  }
};

데이터 사용

[문자열의 경우]

const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('my-key');
    if (value !== null) {
      // value previously stored
    }
  } catch (e) {
    // error reading value
  }
};

[Object의 경우]

const getData = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('my-key');
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch (e) {
    // error reading value
  }
};

삭제

 AsyncStorage.clear();

import { Alert, Button, Text, TextInput, View } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import React, { useEffect, useState } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage';
// import

const Join = () => {
  const [todos, setTodos] = useState([]);
  const [text,setText] = useState("")
  // 변수 설정 => todos = asyncStorage로 받아온 값을 저장할 용도
  // text => input에 입력하는 값을 저장할 용도
   
  
  // --------------------------------------------------
  // AsyncStorage로 Item set/get
  const setData = async (value) => {
    try {
      const jsonValue = JSON.stringify(value);
      await AsyncStorage.setItem('todo', jsonValue);
      Alert.alert("setData 됨")
    } catch (e) {
      console.log(e);
    }
  };

  const getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('todo');
      Alert.alert("getData 됨")
      setTodos(jsonValue != null ? JSON.parse(jsonValue) : [])
    } catch (e) {
      console.log(e);
    }
  };
  
 // --------------------------------------------------
 // 버튼을 클릭했을때, setData 및 getData 실행
  const onPress = () =>{
    const new_value = {
      id: todos.length+1,
      text
    }
    setData(todos.concat(new_value));
    getData();
  }
 // --------------------------------------------------
 // 화면이 rendering 되었을 때 getData() 실행
  useEffect(()=>{
    getData()
  },[])

  
 // --------------------------------------------------
 // --------------------------------------------------
  return (
    <View>
      <Icon name="person" size={30} color="#4F8EF7"/>
      <Text>Join</Text>

      <TextInput
        onChangeText={setText}
      />
      <Button
        title='작성'
        onPress={onPress}
      />
      { todos.map((v)=><Text>{v.id}: {v.text}</Text>)}
    </View>
  )
}

export default Join

profile
sumin0gig

0개의 댓글