Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  171] [ 5]  / answers: 1 / hits: 11054  / 3 Years ago, sat, july 10, 2021, 12:00:00

I am trying to build a react app and want to call a function like this:


if (typeof window !== 'undefined') { var token = (await getItem('secure_token')); }
if (typeof window !== 'undefined') { var user_id = (await getItem('user_id')); }

I am getting error that:


Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)

How can I achieve that. because without await, I am getting [object Promise] and not the actual value.


Below is the complete code:


import axios from "axios";
import { getStorage } from "../../components/Helper";
const API_URL = "http://127.0.0.1:8000/api";
const BASE_API = "http://127.0.0.1:8000";
var token = null;
var user_id = null;
if (typeof window !== 'undefined') { var token = (await getItem('secure_token')); }
if (typeof window !== 'undefined') { var user_id = (await getItem('user_id')); }
export const API_ROUTE = axios.create({
baseURL: API_URL,
withCredentials: true,
crossdomain: true,
headers: {
"Key": token,
"Id": user_id
}
});

export const csrf_token = async () => {
await axios.get(BASE_API + '/sanctum/csrf-cookie');
}

async function getItem(item) {
var data = await getStorage(item);
return data;
}

More From » reactjs

 Answers
9

You can do this to export a function dependent on a promise :


let getTokens = async () => {
var token = null;
var user_id = null;
if (typeof window !== 'undefined') { token = (await getItem('secure_token')); }
if (typeof window !== 'undefined') { user_id = (await getItem('user_id')); }

return {token, user_id };
}


export const API_ROUTE = getTokens().then((data)=> { return axios.create({
baseURL: API_URL,
withCredentials: true,
crossdomain: true,
headers: {
"Key": data.token,
"Id": data.user_id
}
}); });


You can use this promise to access the axios instance in your module.


[#1119] Saturday, July 3, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daquanmilesw

Total Points: 57
Total Questions: 102
Total Answers: 110

Location: Wallis and Futuna
Member since Sat, Aug 6, 2022
2 Years ago
daquanmilesw questions
;