Постоянное хранение не работает на user_id, но работает на access_token - PullRequest
1 голос
/ 06 июля 2019

Я пытаюсь сохранить свой идентификатор пользователя, который я получаю с моего сервера через функцию выборки.Я могу сохранить токен доступа, который я получаю ОДНАКО, я не могу сделать то же самое для моего идентификатора пользователя.

Вот как я получаю идентификатор пользователя из серверной части:

  async onRegisterPressed() {
    try {
      let response = await fetch('SERVER_URL', {
                              method: 'POST',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                              },
                              body: JSON.stringify({
                                user:{
                                  email: (this.state.email).toLowerCase(),
                                  password: this.state.password,
                                  password_confirmation: this.state.password_confirmation,
                                }
                              })
                            });
      let res = await response._bodyText;
      if (response.status >= 200 && response.status < 300) {
        this.storeToken(JSON.parse(res).data.user.authentication_token)
        this.storeID((JSON.parse(res).data.user.id).toString())
        this.redirect(JSON.parse(res).data.user.authentication_token, this.state.email, (JSON.parse(res).data.user.id).toString())
      } else {
          let error = res;
          this.setState({ error: 'Please try again' })
          throw error;
      }
    } catch(errors) {
        this.removeToken()
        this.setState({ error: 'Oops, try again' })
      }
    }

Следующие функции используются для постоянного хранения электронной почты, токена доступа (и попытки сохранить пользователяid):


const ACCESS_TOKEN = 'authentication_token'
const USER_ID = 'id'


  persistData() {
    console.log('persistData function')
    let email = this.state.email
    let accessToken = this.state.accessToken

    AsyncStorage.setItem('email', email)
    AsyncStorage.setItem('accessToken', accessToken)
  }


  persistID() {
    console.log('persistID function')
    let userId = this.state.userId

    AsyncStorage.setItem('userId', userId)
  }


  redirect(accessToken, email, id) {
    console.log('redirect function')
    this.props.navigation.navigate(
      'Home',
      { accessToken: accessToken, 
        email: email,
        userId: id,
        onLogout: () => this.clearData()
      }
    )
  }

    async storeToken(accessToken) {
      console.log('storeToken function')
      try {
        await AsyncStorage.setItem(ACCESS_TOKEN, accessToken)
        this.getToken()
        this.setState({accessToken: accessToken})
        this.persistData()
      } catch(error) {
        console.log('ERROR STORE TOKEN')
      }
    }

    async storeID(userId) {
      console.log('storeID function')
      try {
        await AsyncStorage.setItem(USER_ID, userId)
        this.getID()
        this.setState({userId: userId})
        this.persistID()
      } catch(error) {
        console.log('ERROR STORE TOKEN')
      }
    }

    async getID() {
      console.log('getID function')
      try {
        let id = await AsyncStorage.getItem(USER_ID)
      } catch(error) {
        console.log('GET TOKEN ERROR')
      } 
    }

    async getToken() {
      console.log('getToken function')
      try {
        let token = await AsyncStorage.getItem(ACCESS_TOKEN)
      } catch(error) {
        console.log('GET TOKEN ERROR')
      }
    }

...