New to development. Trying to use Firebase Messaging with a ReactJS app. I want to add the token to my headers so I can send to the backend:
instance.interceptors.request.use(
(config) => {
const token = TokenService.getLocalAccessToken();
const firebaseToken = getNewToken();
if (token) {
// config.headers["Authorization"] = 'Bearer ' + token; // for Spring Boot back-end
config.headers["x-access-token"] = token; // for Node.js Express back-end
config.headers["firebase-token"] = firebaseToken;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
..getToken points to the below:
export const getNewToken = async () => {
let currentToken = '';
try {
currentToken = await getToken(messaging, {vapidKey: "MY_VAPID_KEY"});
if (currentToken) {
console.log(currentToken);
//setTokenFound(true);
} else {
//setTokenFound(false);
}
} catch (error) {
console.log('An error occurred while retrieving token.', error);
}
return currentToken;
};
…And this shows the token in the console log correctly, but it is returned to headers as [object Promise] and I’m not sure what to do about it. I know this has something to do with the asynchronous nature of Promises and I have experimented with doing this using async/await functions – but the result is always the same. Any ideas?
2
Answers
I had to update my axios instance interceptor as such, adding async/await:
You forgot to use
await
and that’s it.While calling an async function, you must
await
it to get the returned value.