'How can i assign token in async storage to headers in app.js after login. in react-native
I am getting access token after login and I want to assign that token to authorization in headers in my App.js I am using async storage to store the access token in local storage and I want to assign to headers in my App.js file How can I do it. I want to assign token to authorization in headers so that I can make graphql API calls
MY App.js file
import React, {Component} from 'react';
import {AppRegistry,SafeAreaView, StyleSheet} from 'react-native';
import Navigator from "@Navigation"
import AsyncStorage from '@react-native-community/async-storage';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-boost';
const httpLink = createHttpLink({
uri: 'https://graphql.sample.com/graphql',
});
const token = AsyncStorage.getItem('@accessToken')
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ,
}
}
});
const link = authLink.concat(httpLink)
const cache = new InMemoryCache();
const defaultOptions = {
query: {
fetchPolicy: "network-only",
errorPolicy: "all"
}
};
const client = new ApolloClient({
link,
cache,
defaultOptions
});
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Navigator/>
</ApolloProvider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
export default App;
Solution 1:[1]
Changing the authLink function to work with async/await worked for me! Hope this helps;
const authLink = setContext(async (_, { headers }) => {
// get the authentication token from async storage if it exists
const accessToken = await AsyncStorage.getItem('@accessToken');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: accessToken ? `Bearer ${accessToken}` : '',
},
};
});
Solution 2:[2]
You should await AsyncStorage.getItem('@accessToken')
to get your accessToken before passing it to authorization: token
. This is a post relating to Waiting for AsyncStorage.getItem()
in React Native.
Try this:
...
const token = await AsyncStorage.getItem('@accessToken')
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ,
}
}
});
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | andrewdyer |
Solution 2 | Michael |