Skip to content

Instantly share code, notes, and snippets.

@boniattirodrigo
Created June 25, 2017 18:44
Show Gist options
  • Save boniattirodrigo/b249daf7a6b71ad16edd7704fd76a43b to your computer and use it in GitHub Desktop.
Save boniattirodrigo/b249daf7a6b71ad16edd7704fd76a43b to your computer and use it in GitHub Desktop.
A simple process to get, store and delete values from AsyncStorage.
import React, { Component } from 'react'
import {
View,
AsyncStorage,
TouchableHighlight,
Text,
StyleSheet,
} from 'react-native'
const ACCESS_TOKEN = 'access_token'
export default class Login extends Component {
storeToken(tokenValue) {
AsyncStorage.setItem(ACCESS_TOKEN, tokenValue, err => {
if (err) { console.log(`The error is: ${err}`) }
})
.catch(err => console.log(`The error is: ${err}`))
}
async getToken(callback) {
try {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN)
callback(accessToken)
} catch (err) {
console.log(`The error is: ${err}`)
}
}
async deleteToken() {
try {
await AsyncStorage.removeItem(ACCESS_TOKEN)
} catch (err) {
console.log(`The error is: ${err}`)
}
}
async onLoginPressed() {
this.getToken(result => {
if (result) {
console.log('I already have a token')
console.log(result)
} else {
console.log('I do not have a token and I need to create it.')
this.storeToken('123456')
}
})
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
style={styles.button}
onPress={this.onLoginPressed.bind(this)}>
<Text style={styles.buttonText}>
Login
</Text>
</TouchableHighlight>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#CCC',
},
button: {
height: 50,
backgroundColor: '#48BBEC',
alignSelf: 'stretch',
marginTop: 10,
justifyContent: 'center'
},
buttonText: {
fontSize: 22,
color: '#FFF',
alignSelf: 'center'
},
});
@Tamil1993
Copy link

first one value is store, after that value is get, and how to delete a get value when once i get a value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment