How can I do top level await

Viewed 7024

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;
}
3 Answers

Currently there is no top level await support present in react and as far as I know only Deno supports top level await. So to overcome your problem all you can do is to use IIFE i.e., immediate invoked function expression to solve your problem in the below manner:

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

You can wrap your code in the async function and immediately execute it

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

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.

Related