React Native에서 AsyncStorage 사용하기

citron03·2022년 10월 11일
2

React Native

목록 보기
5/7
  • 앱을 종료 후 다시 실행하였을 때, 데이터가 남아있지 않는 문제가 있을 수 있다.
  • 이때, 브라우저의 localStorage처럼 key-value기반으로 로컬에 데이터를 저장할 수 있게 해주는 라이브러리를 사용한다.
  • @react-native-async-storage/async-storage
  • localstorage와 마찬가지로, 문자열 데이터만 사용이 가능하다.
  • 따라서 JSON.stringify 메서드와 JSON.parse 메서드의 사용이 필요하다.
  • 하지만 AsyncStorage는 localstorage와는 다르게 비동기 처리가 필요하다.
  • 다음과 같이 사용할 수 있다.
import React, { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { ScrollView, TextInput, StyleSheet, Text } from "react-native";
import Item from "./Item";

const List = () => {
    const [textData, setTextData] = useState("");
    const [listData, setListData] = useState([]);
    
    const handleSubmit = async () => {
        const newList = [{title: textData, content: textData},
        				...listData];
        await AsyncStorage.setItem("textData", JSON.stringify(newList));
        setListData(newList);
        setTextData("");
        alert("등록");
    }
    
    useEffect(() => {
        const getData = async () => {
            const storageData = 
            	JSON.parse(await AsyncStorage.getItem("textData"));
            if(storageData) {
                console.log("GET data from storage");
                setListData(storageData);
            }
        }
        // AsyncStorage에 저장된 데이터가 있다면, 불러온다.
        getData();
    }, []);
    
    return (
        <ScrollView>
            {listData.length > 0 ? 
                listData.map((el, idx) => 
                    <Item 
                       	key={idx}                     
                    	title={el.title} 
                        content={el.content} 
                    />)
                    : <Text>데이터가 없습니다.</Text>}
            <TextInput 
                style={styles.TextInputStyle} 
                placeholder="title"
                defaultvalue={textData}
                value={textData}
                onChangeText={(text) => setTextData(text)}
                onSubmitEditing={handleSubmit}
            />
        </ScrollView>
    );
}

const styles = StyleSheet.create({
    TextInputStyle: {
        fontSize: 20,
        padding: 15,
        margin: 10,
        borderWidth: 1,
    }
});

export default List;
profile
🙌🙌🙌🙌

0개의 댓글