본문 바로가기

React Native

[React Native] Async Storage - setItem, getItem, 중복확인 검사

반응형

 아이디, 비번, 닉네임 변경 부분을 맡았따.

 변경 후에 비번과 닉네임은 async storage부분에도 변경을 해줘야 했다.

 id는 asyncstorage를 삭제하고 다시 로그인하라고 로그인 페이지로 보낸다

그래서 해보았다

 

 


 

1. 기본적인 코드

import { AsyncStorage } from 'react-native'; //Library

//Persisting data
_storeData = async () => {
  try {
    await AsyncStorage.setItem(
      '@MySuperStore:key',
      'I like to save it.'
    );
  } catch (error) {
    // Error saving data
  }
};

//Fetching data
_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('TASKS');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};

 

 

2. 내꺼

 

1)getItem

componentWillMount() {
    AsyncStorage.getItem('login_user_info', (err, result) => {
      const UserInfo = JSON.parse(result);
      this.setState({
        key: UserInfo.user_key,
        email: UserInfo.user_email,
      });
      const post = {
        key: UserInfo.user_key,
      };
      fetch(func.api(3001, 'call'), {
        method: 'post',
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify(post),
      })
        .then((res) => res.json())
        .then((json) => {
          this.setState({
            id: json.user_id,
            nickname: json.user_nickname,
            sex: json.user_sex,
            deptno: json.user_deptno,
            stdno: json.user_stdno,
          });
        });
    });
    console.log(this.state.stdno);
  }

 login할때에 'login_user_info'Async Storage에 데이터를 setItem해준다. 

거기서 key와 이메일을 가져와서 데이터베이스에 접근하여 가져온 user_key를 사용하여 id, nickname, sex(성별), deptno(학과), stdno(학번)을 가져와 state값에 저장해준다.

 

2) id 변경 코드

Set_privacy.js

  check = (re, what, message) => {
    if (re.test(what)) {
      return true;
    }
    alert(message);
    return false;
  };
// 아이디 중복검사
  checkId = (e) => {
    e.preventDefault();
    var re = /^[a-zA-Z0-9]{4,12}$/; //아이디는 4~12자의 영문 대소문자와 숫자로만 입력
    if (
      !this.check(
        re,
        this.state.id,
        '아이디는 4~12자의 영문 대소문자와 숫자로만 입력가능합니다.',
      )
    ) {
      return;
    } else {
      const checkId = {
        id: this.state.id,
      };
      fetch(func.api(3001, 'CheckId'), {
        method: 'post',
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify(checkId),
      })
        .then((res) => res.json())
        .then((json) => {
          if (json) {
            alert('사용가능한 아이디 입니다.');
            this.setState({
              checked_id: true,
            });
          } else {
            alert('이미 사용중인 아이디 입니다.');
          }
        });
    }
  };
  // 아이디 변경
  changeId = (e) => {
    e.preventDefault();
    const changeId = {
      key: this.state.key,
      id: this.state.id,
    };
    fetch(func.api(3001, 'ChangeId'), {
      method: 'post',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify(changeId),
    })
      .then((res) => res.json())
      .then((json) => {
        if (json) {
          alert('아이디가 변경되었습니다.');
          this.setState({
            checked_id: false,
          });
          AsyncStorage.clear();
          this.props.navigation.navigate('Login');
        } else {
          alert('id 변경 실패 버그 신고');
        }
      });
  };

server.js

//아이디 중복검사
app.post('/CheckId', (req, res) => {
  const checkId = req.body.id;
  console.log(checkId);
  connection.query(
    'SELECT user_id FROM user_table WHERE user_id =(?)',
    [checkId],
    function (err, rows, fields) {
      if (rows[0] === undefined) {
        console.log('CheckId true');
        res.send(true); //중복 없음 사용가능
      } else {
        console.log('CheckId false');
        res.send(false); // 중복 있음 사용안됨
      }
    },
  );
});

//아이디 변경
app.post('/ChangeId', (req, res) => {
  const changeId = req.body.id;
  const key = req.body.key;
  // console.log(ChangeId);
  connection.query(
    'UPDATE user_table SET user_id = (?) WHERE user_key =(?)',
    [changeId, key],
    function (err, rows, fields) {
      if (err) {
        console.log('changeid error' + err);
      } else {
        console.log('changed good');
        res.send(true);
      }
    },
  );
});

 아이디 중복검사 checkId함수와 아이디 변경 changeId함수를 통해 디비와 통신한다.

<View style={styles.Id_privacy}>
  <Text style={styles.Textid_privacy}>아이디</Text>
  <View style={{display: 'flex', flexDirection: 'row'}}>
    <TextInput
      style={styles.Id_input_privacy}
      id="id"
      value={this.state.id}
      onChangeText={(text) => this.setState({id: text, checked_id: false})}
    />
    {this.state.checked_id === false ? (
      <TouchableOpacity style={styles.Btn_privacy} onPress={this.checkId}>
        <Text
          style={{
            color: 'gray',
            fontFamily: 'Jalnan',
            fontSize: 15,
          }}>
          중복확인
        </Text>
      </TouchableOpacity>
    ) : (
      <TouchableOpacity style={styles.Btn_privacy} onPress={this.changeId}>
        <Text
          style={{
            color: 'gray',
            fontFamily: 'Jalnan',
            fontSize: 15,
          }}>
          변경하기
        </Text>
      </TouchableOpacity>
    )}
  </View>
</View>;

 onChange함수를 쓰면 checked_id(중복확인검사)가 false가 되게 했다.

 이게 없으면 중복검사를 하고 있는 아이디로 변경이 가능해진다.

예를 들어 있는 아이디 : hyuk // 중복확인 받은 아이디 : hyuk1  

hyuk1로 중복확인을 받은 후 hyuk으로 아이디를 변경하면 변경이 된다. 그래서 onChange함수에 checked_id에 false값을 넣었다.

또한 삼항 연산자를 사용하여 checked_id === false이면 중복확인 버튼이 나오고 true면 변경하기 버튼을 나오게 만들었다.

 

 위에서 말한 것과 같이 id는 변경후에 다시 로그인해달라고 하고 로그인 페이지로 이동한다. 그 코드는 set_privacy 65~66줄이다.

AsyncStorage.clear();
this.props.navigation.navigate('Login');

이 부분이다.

3) SetItem

 setItem은 닉네임으로 알아보자.

다른 부분은 동일하다. 닉네임 변경 함수 changenickname을 보자

  //닉네임 바꾸기
  changenickname = (e) => {
    e.preventDefault();
    const changenickname = {
      key: this.state.key,
      nickname: this.state.nickname,
    };
    fetch(func.api(3001, 'ChangeNickname'), {
      method: 'post',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify(changenickname),
    })
      .then((res) => res.json())
      .then((json) => {
        if (json) {
          alert('닉네임이 변경되었습니다.');
          this.setState({
            nickname_check: false,
          });
        } else {
          alert('nickname 변경 실패 버그 신고');
        }
      });
    AsyncStorage.setItem(
      'login_user_info',
      JSON.stringify({
        user_nickname: this.state.nickname,
        user_key: this.state.key,
        user_id: this.state.id,
        user_sex: this.state.sex,
        user_email: this.state.email,
        user_deptno: this.state.deptno,
        user_stdno: this.state.stdno,
      }),
    );
  };

제일 밑 코드 부분을 보면 AsyncStorage 'login_user_info'라는 저장소에 user_nickname, key, id, sex 등을 저장한다. 

 

 

이렇게 Async Storage 이름을 마음대로 정하고 거기서 필요한 정보들을 꺼내와서 더욱 쉽고 재밌는 코딩이 되봅시다

 

오늘하루도 열코입니당!!!!!!!!!!!! 

반응형