본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/HybridApp

HybridApp-React Native 2세대 (기능 - AsyncStorage API )

by 차누감 2020. 1. 29.

<최종 화면>

1. AsyncStorage를 이용하여 데이터를 저장하고 불러온다.

2. AsyncStorage를 이용하여 데이터를 저장하고 불러온다. 추가로 await 사용 

( AsyncStorage는 비동기라서 순서의 문제가 생길 수 있다. 저장하는 동안 다른 작업을 진행하므로... AsyncStorage을 할 동안 잠깐 메인 스레드를 대기하게 만든다. )


d\hybridapp\reactnative 경로에서 RN17AsyncStorage를 만들어서 작업하자.

asyncstorage를 사용하기 위해 아래 해당 사이트를 가보자.

이제는 AsyncStorage를 사용하려면 community에서 공유하는 것을 사용해야한다.

새탭으로 열어서 보면 어떻게 사용하는지 나와있다. 우선 install을 해주자.

아까 init한 폴더로 들어가서 install 하자.

코드 작성 이전에 우선 run을 먼저 하고 코드 작성을 하자. 

( 이유 : 코드가 문제인지 install이 잘못된 것인지 나중에 찾기 힘들다. )

우선 화면에 버튼과 여러 요소를 배치하자.

스타일을 주자.

saveData 버튼을 누르면 this.state.inputText의 값이 저장된다. 그리고 다이얼로그 창이 뜬다.

this.state.inpuText는 화면 Textinput에 입력할때마다 저장이 된다.

save Data 버튼을 누렀을때 입력창에 값을 지우려면

inputText의 값만 바꾸면 안된다. <TextInput>에 입력되는 값이 value 속성 값에 입력되기 때문에 value 속성값도 변경해야 한다.

load Data 버튼에 대한 기능을 만들자.

AsyncStorage에 저장된 값을 가져와서  <Text>에 보여주자.

새로 버튼을 만들어 보자. 이전의 버튼들은 다소 문제가 있을 수 있다. AsyncStorage는 비동기 방식이므로 저장을 할때 메인 스레드는 다른 작업을 한다. 그래서 .then() 처럼 AsyncStorage가 끝날때 까지 대기하게 만들 수 있다.

메소드 앞에 async를 써주고 대기할 곳에 await을 써주자.

<복붙용 코드>

Main.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

import React, {Component} from 'react';

import {View, Text, Button, TextInput,StyleSheet} from 'react-native';

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

 

export default class Main extends Component{

 

    constructor(){

        super();

        this.state={

            inputText:"",

            text:"",

        }

    }

 

    render(){

        return(

            <View style={styles.root}>

                  <TextInput 

                        style={styles.textInput}

                        placeholder="Enter some text here"

                        onChangeText={this.changeText}

                        value={this.state.inputText}>

                    </TextInput>

                  <Button title="save data" onPress={this.saveData}></Button>

 

                  <View style={{marginTop:16,}}></View>

 

                  <Button title="load data" color="orange" onPress={this.loadData}></Button>

                  <Text style={styles.text}>{this.state.text}</Text>

 

                  <Button title="storage data" color="indigo" onPress={this.storageData}></Button>

                  <Button title="get data" color="green" onPress={this.getData}></Button>

            </View>

        );

    }//render method..

 

    // 텍스트인풋에 값이 변경될때 마다 호출되는 함수로 지정된 메소드

    changeText=(value)=>//파라미터 : 변경된 데이터

        this.setState({inputText:value});

    }//changeText method..

    saveData=()=>{

        // state.inputText 변수에 저장된 입력값을 영구적으로 저장하기 위해

        //AsyncStorage에 저장 [Android의 SharedPrefereneces와 거의 같음]

        AsyncStorage.setItem('Data'this.state.inputText); //[키,벨류]

        alert('saved data');

 

        // 다음 입력이 편하도록 TextInput에 써있는 글씨 제거

        this.setState({inputText:""});

    }

    loadData=()=>{

        //키 값을 이용해서 저장된 값 읽어오기

        // 비동기 방식이므로 명령을 호출하자마자 결과가 오지 않음

        // 즉, 리턴으로 결과를 받지 못함.. 그래서 promiss문법 사용 .then()메소드 사용

        AsyncStorage.getItem('Data').then((value)=>{this.setState({text:value})});

    }

 

    storageData= async ()=>{

        //ES7 버전에서 도입된 문법 : async await 문법

        await AsyncStorage.setItem('msg',"Hello React Native");

        alert('saved Data');

        this.setState({inputText:""});

    }

 

    getData=async()=>{

        const msg= await AsyncStorage.getItem('msg');

        if(msg != null) this.setState({text:msg});

    }

}//Main class..

 

const styles=StyleSheet.create({

    root:{flex:1, padding:16},

    textInput:{

        paddingLeft:16,

        paddingRight:16,

        borderWidth:1,

        borderRadius:8,

        borderColor:'black',

        marginBottom:16,

    },

    text:{

        marginTop:16,

        padding:8,

        fontWeight:'bold',

    }

});

 

 

댓글