我正在尝试存储我的用户ID,该ID是通过获取功能从服务器上获取的。我能够存储访问令牌,但是我无法为我的userId做同样的事情。
这是我从后端获取用户ID的方式:
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')
}
}