ronan
December 14, 2022, 1:19pm
1
Hello all,
I am creating an app on Expo React Native
I am using Auth0 on my app. And I am trying to authenticate a user with the Auth0 from 8base
Doing this
await authorize();
const { accessToken } = await getCredentials();
await AsyncStorage.setItem("@token", accessToken);
Then I get that accessToken and put it in the header of my Apollo client
const token = await AsyncStorage.getItem("@token");
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
Then I query the user with this token
const [getUser, { loading, data, onCompleted }] = useLazyQuery(QUERY, {
onCompleted(data) {
console.log("get User completed");
console.log(data);
setUser(data.user);
},
onError(error) {
console.log(error);
},
});
getUser()
And I get this error : [Error: Token validation]
I am doing it the right way ?
Thanks for your help !!
Hey there!
You can create a hook for handle the requests with token.
For example:
You can create a file called useRequestClient.ts
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: process.env.REACT_APP_API_ENDPOINT,
});
const authLink = setContext((_, { headers }) => {
const auth: any = JSON.parse(localStorage.getItem('auth') ?? '{}');
return {
headers: {
...headers,
authorization: auth.token ? `Bearer ${auth.token}` : '',
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export const useRequestClient = () => client;
Where REACT_APP_API_ENDPOINT is your 8base api url like this:
REACT_APP_API_ENDPOINT=https://api.8base.com/${REACT_APP_WORKSPACE_ID}_${REACT_APP_WORKSPACE_ENV}
Also, instead of getting the token from the localStorage, you can use your method to pass the token. Then, you can pass the client as a argument to your query. For example:
const [getUser, { loading, data, onCompleted }] = useLazyQuery(QUERY, {
client,
onCompleted(data) {
console.log("get User completed");
console.log(data);
setUser(data.user);
},
onError(error) {
console.log(error);
},
});
Hope it helps. Any doubts, you can reply me.