Use AsyncStorage to store token globally
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I'm learning react-native since one week and i'm confused about something.
Here is the stuff:
I'm developing an app parsing Imgur API, I somehow managed via a Webview to authenticate myself and get an accessToken, refreshToken etc which I stored locally on my webview component.
Now I want to store this token globally on the app so I did some research and found about AsyncStorage (visibly not secure to store tokens but it's fine it's just an app to practice).
So here is what I understood:
- You give a key and a value via setItem, they wrap it somehow in a Promise (I need to do some research about this stuff)
- Then you can get it back in another async function.
So here is what I did to set my item in my Login component:
//login.js
import React from 'react'
import {AsyncStorage, StyleSheet, WebView} from 'react-native'
import { StackActions, NavigationActions } from 'react-navigation';
const webviewRef = 'webview';
const CLIENT_ID = 'xxxxxxx';
class LoginImgur extends React.Component {
accessToken : string;
expiresIn : string;
refreshToken : string;
userName : string;
constructor(props) {
super(props);
}
async storeItem(key, item) {
try {
let jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
return jsonOfItem;
} catch (error) {
console.log(error.message);
}
}
_resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Index' })],
});
_changeNavigationState = async (webView) => {
if (this._splitUrl(webView.url) === true) {
console.log(this.accessToken);
let json = this.storeItem('ACCESS_TOKEN', this.accessToken);
this.props.navigation.dispatch(this._resetAction);
}
};
_splitUrl(url : String) {
if (url.search("access_token=") > 0) {
let array = url.split("=");
this.accessToken = array[2].split('&')[0];
this.expiresIn = array[3].split('&')[0];
this.refreshToken = array[5].split('&')[0];
this.userName = array[6].split('&')[0];
return (true);
}
return (false);
}
webviewProps = {
style: styles.webview_container,
ref: webviewRef,
javaScriptEnabled: true,
onNavigationStateChange: this._changeNavigationState.bind(this),
source: {
uri: 'https://api.imgur.com/oauth2/authorize?client_id=' + CLIENT_ID + '&response_type=token&state=APPLICATION_STATE',
}
};
render() {
return (
<WebView {...this.webviewProps}/>
)
}
}
const styles = StyleSheet.create({
main_container: {
backgroundColor: 'black'
},
webview_container: {
flex: 1
}
});
export default LoginImgur
So now I'm in my homescreen and I want to get this accessToken back so I can now make my API calls !!
// Index.js
class Index extends React.Component {
accessToken : string;
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.log(error.message);
}
}
constructor(props) {
super(props);
}
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.accessToken = value;
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
_displayAccessToken() {
console.log(this.accessToken);
}
render() {
return (
<View>
{this._displayAccessToken()}
<Text>Lol</Text>
</View>
)
}
}
But... It's not working at all. I do get the token in the console.log actually but it doesn't get save in my this.accessToken.
Someone have an idea to pull it of ? Would be a great help... enter image description here
javascript react-native async-await
add a comment |
I'm learning react-native since one week and i'm confused about something.
Here is the stuff:
I'm developing an app parsing Imgur API, I somehow managed via a Webview to authenticate myself and get an accessToken, refreshToken etc which I stored locally on my webview component.
Now I want to store this token globally on the app so I did some research and found about AsyncStorage (visibly not secure to store tokens but it's fine it's just an app to practice).
So here is what I understood:
- You give a key and a value via setItem, they wrap it somehow in a Promise (I need to do some research about this stuff)
- Then you can get it back in another async function.
So here is what I did to set my item in my Login component:
//login.js
import React from 'react'
import {AsyncStorage, StyleSheet, WebView} from 'react-native'
import { StackActions, NavigationActions } from 'react-navigation';
const webviewRef = 'webview';
const CLIENT_ID = 'xxxxxxx';
class LoginImgur extends React.Component {
accessToken : string;
expiresIn : string;
refreshToken : string;
userName : string;
constructor(props) {
super(props);
}
async storeItem(key, item) {
try {
let jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
return jsonOfItem;
} catch (error) {
console.log(error.message);
}
}
_resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Index' })],
});
_changeNavigationState = async (webView) => {
if (this._splitUrl(webView.url) === true) {
console.log(this.accessToken);
let json = this.storeItem('ACCESS_TOKEN', this.accessToken);
this.props.navigation.dispatch(this._resetAction);
}
};
_splitUrl(url : String) {
if (url.search("access_token=") > 0) {
let array = url.split("=");
this.accessToken = array[2].split('&')[0];
this.expiresIn = array[3].split('&')[0];
this.refreshToken = array[5].split('&')[0];
this.userName = array[6].split('&')[0];
return (true);
}
return (false);
}
webviewProps = {
style: styles.webview_container,
ref: webviewRef,
javaScriptEnabled: true,
onNavigationStateChange: this._changeNavigationState.bind(this),
source: {
uri: 'https://api.imgur.com/oauth2/authorize?client_id=' + CLIENT_ID + '&response_type=token&state=APPLICATION_STATE',
}
};
render() {
return (
<WebView {...this.webviewProps}/>
)
}
}
const styles = StyleSheet.create({
main_container: {
backgroundColor: 'black'
},
webview_container: {
flex: 1
}
});
export default LoginImgur
So now I'm in my homescreen and I want to get this accessToken back so I can now make my API calls !!
// Index.js
class Index extends React.Component {
accessToken : string;
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.log(error.message);
}
}
constructor(props) {
super(props);
}
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.accessToken = value;
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
_displayAccessToken() {
console.log(this.accessToken);
}
render() {
return (
<View>
{this._displayAccessToken()}
<Text>Lol</Text>
</View>
)
}
}
But... It's not working at all. I do get the token in the console.log actually but it doesn't get save in my this.accessToken.
Someone have an idea to pull it of ? Would be a great help... enter image description here
javascript react-native async-await
add a comment |
I'm learning react-native since one week and i'm confused about something.
Here is the stuff:
I'm developing an app parsing Imgur API, I somehow managed via a Webview to authenticate myself and get an accessToken, refreshToken etc which I stored locally on my webview component.
Now I want to store this token globally on the app so I did some research and found about AsyncStorage (visibly not secure to store tokens but it's fine it's just an app to practice).
So here is what I understood:
- You give a key and a value via setItem, they wrap it somehow in a Promise (I need to do some research about this stuff)
- Then you can get it back in another async function.
So here is what I did to set my item in my Login component:
//login.js
import React from 'react'
import {AsyncStorage, StyleSheet, WebView} from 'react-native'
import { StackActions, NavigationActions } from 'react-navigation';
const webviewRef = 'webview';
const CLIENT_ID = 'xxxxxxx';
class LoginImgur extends React.Component {
accessToken : string;
expiresIn : string;
refreshToken : string;
userName : string;
constructor(props) {
super(props);
}
async storeItem(key, item) {
try {
let jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
return jsonOfItem;
} catch (error) {
console.log(error.message);
}
}
_resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Index' })],
});
_changeNavigationState = async (webView) => {
if (this._splitUrl(webView.url) === true) {
console.log(this.accessToken);
let json = this.storeItem('ACCESS_TOKEN', this.accessToken);
this.props.navigation.dispatch(this._resetAction);
}
};
_splitUrl(url : String) {
if (url.search("access_token=") > 0) {
let array = url.split("=");
this.accessToken = array[2].split('&')[0];
this.expiresIn = array[3].split('&')[0];
this.refreshToken = array[5].split('&')[0];
this.userName = array[6].split('&')[0];
return (true);
}
return (false);
}
webviewProps = {
style: styles.webview_container,
ref: webviewRef,
javaScriptEnabled: true,
onNavigationStateChange: this._changeNavigationState.bind(this),
source: {
uri: 'https://api.imgur.com/oauth2/authorize?client_id=' + CLIENT_ID + '&response_type=token&state=APPLICATION_STATE',
}
};
render() {
return (
<WebView {...this.webviewProps}/>
)
}
}
const styles = StyleSheet.create({
main_container: {
backgroundColor: 'black'
},
webview_container: {
flex: 1
}
});
export default LoginImgur
So now I'm in my homescreen and I want to get this accessToken back so I can now make my API calls !!
// Index.js
class Index extends React.Component {
accessToken : string;
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.log(error.message);
}
}
constructor(props) {
super(props);
}
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.accessToken = value;
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
_displayAccessToken() {
console.log(this.accessToken);
}
render() {
return (
<View>
{this._displayAccessToken()}
<Text>Lol</Text>
</View>
)
}
}
But... It's not working at all. I do get the token in the console.log actually but it doesn't get save in my this.accessToken.
Someone have an idea to pull it of ? Would be a great help... enter image description here
javascript react-native async-await
I'm learning react-native since one week and i'm confused about something.
Here is the stuff:
I'm developing an app parsing Imgur API, I somehow managed via a Webview to authenticate myself and get an accessToken, refreshToken etc which I stored locally on my webview component.
Now I want to store this token globally on the app so I did some research and found about AsyncStorage (visibly not secure to store tokens but it's fine it's just an app to practice).
So here is what I understood:
- You give a key and a value via setItem, they wrap it somehow in a Promise (I need to do some research about this stuff)
- Then you can get it back in another async function.
So here is what I did to set my item in my Login component:
//login.js
import React from 'react'
import {AsyncStorage, StyleSheet, WebView} from 'react-native'
import { StackActions, NavigationActions } from 'react-navigation';
const webviewRef = 'webview';
const CLIENT_ID = 'xxxxxxx';
class LoginImgur extends React.Component {
accessToken : string;
expiresIn : string;
refreshToken : string;
userName : string;
constructor(props) {
super(props);
}
async storeItem(key, item) {
try {
let jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
return jsonOfItem;
} catch (error) {
console.log(error.message);
}
}
_resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Index' })],
});
_changeNavigationState = async (webView) => {
if (this._splitUrl(webView.url) === true) {
console.log(this.accessToken);
let json = this.storeItem('ACCESS_TOKEN', this.accessToken);
this.props.navigation.dispatch(this._resetAction);
}
};
_splitUrl(url : String) {
if (url.search("access_token=") > 0) {
let array = url.split("=");
this.accessToken = array[2].split('&')[0];
this.expiresIn = array[3].split('&')[0];
this.refreshToken = array[5].split('&')[0];
this.userName = array[6].split('&')[0];
return (true);
}
return (false);
}
webviewProps = {
style: styles.webview_container,
ref: webviewRef,
javaScriptEnabled: true,
onNavigationStateChange: this._changeNavigationState.bind(this),
source: {
uri: 'https://api.imgur.com/oauth2/authorize?client_id=' + CLIENT_ID + '&response_type=token&state=APPLICATION_STATE',
}
};
render() {
return (
<WebView {...this.webviewProps}/>
)
}
}
const styles = StyleSheet.create({
main_container: {
backgroundColor: 'black'
},
webview_container: {
flex: 1
}
});
export default LoginImgur
So now I'm in my homescreen and I want to get this accessToken back so I can now make my API calls !!
// Index.js
class Index extends React.Component {
accessToken : string;
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.log(error.message);
}
}
constructor(props) {
super(props);
}
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.accessToken = value;
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
_displayAccessToken() {
console.log(this.accessToken);
}
render() {
return (
<View>
{this._displayAccessToken()}
<Text>Lol</Text>
</View>
)
}
}
But... It's not working at all. I do get the token in the console.log actually but it doesn't get save in my this.accessToken.
Someone have an idea to pull it of ? Would be a great help... enter image description here
javascript react-native async-await
javascript react-native async-await
asked Nov 16 '18 at 21:30
Arthur GamblinArthur Gamblin
31
31
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
await AsyncStorage.getItem(key);
is async: it takes a while before the result is available. render()
runs almost immediately, so at that time this.accessToken
is not set yet.
One option to display the accesstoken is to store it the component's state. When you call this.setState({ accessToken: value })
, render() is called again, so then the value will be rendered as soon as the result is available.
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.setState({accessToken: value }); // cause re-rendering
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
render() {
return (
<View>
<Text>{this.state.accessToken}</Text>
<Text>Lol</Text>
</View>
)
}
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53345673%2fuse-asyncstorage-to-store-token-globally%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
await AsyncStorage.getItem(key);
is async: it takes a while before the result is available. render()
runs almost immediately, so at that time this.accessToken
is not set yet.
One option to display the accesstoken is to store it the component's state. When you call this.setState({ accessToken: value })
, render() is called again, so then the value will be rendered as soon as the result is available.
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.setState({accessToken: value }); // cause re-rendering
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
render() {
return (
<View>
<Text>{this.state.accessToken}</Text>
<Text>Lol</Text>
</View>
)
}
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
add a comment |
await AsyncStorage.getItem(key);
is async: it takes a while before the result is available. render()
runs almost immediately, so at that time this.accessToken
is not set yet.
One option to display the accesstoken is to store it the component's state. When you call this.setState({ accessToken: value })
, render() is called again, so then the value will be rendered as soon as the result is available.
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.setState({accessToken: value }); // cause re-rendering
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
render() {
return (
<View>
<Text>{this.state.accessToken}</Text>
<Text>Lol</Text>
</View>
)
}
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
add a comment |
await AsyncStorage.getItem(key);
is async: it takes a while before the result is available. render()
runs almost immediately, so at that time this.accessToken
is not set yet.
One option to display the accesstoken is to store it the component's state. When you call this.setState({ accessToken: value })
, render() is called again, so then the value will be rendered as soon as the result is available.
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.setState({accessToken: value }); // cause re-rendering
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
render() {
return (
<View>
<Text>{this.state.accessToken}</Text>
<Text>Lol</Text>
</View>
)
}
await AsyncStorage.getItem(key);
is async: it takes a while before the result is available. render()
runs almost immediately, so at that time this.accessToken
is not set yet.
One option to display the accesstoken is to store it the component's state. When you call this.setState({ accessToken: value })
, render() is called again, so then the value will be rendered as soon as the result is available.
componentDidMount() {
this.retrieveItem('ACCESS_TOKEN').then((value) => {
console.log(value);
this.setState({accessToken: value }); // cause re-rendering
}).catch((error) => {
console.log('Promise is rejected with error: ' + error);
});
}
render() {
return (
<View>
<Text>{this.state.accessToken}</Text>
<Text>Lol</Text>
</View>
)
}
answered Nov 16 '18 at 21:52
DirkDirk
1,47421227
1,47421227
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
add a comment |
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
Thanks a lot man that worked :-) !!! But is it not to brutal to put my token in the state ? I mean I don't use it in the render function but just on API related functions. Do you thin of a solution I can work with? Thanks a lot !!
– Arthur Gamblin
Nov 17 '18 at 14:54
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53345673%2fuse-asyncstorage-to-store-token-globally%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown