0

I want to use a Const variable that is inside a function and define it as a new const.

setup() {
    async function recieveData() {
        const result = await fetch(`${import.meta.env.VITE_APP_API_URL}/invoice`, {
            method: "GET",
        });
        const array = await result.json();
    }
}

I need to somehow get the const 'arrayData' from the function

setup() {
    async function recieveData() {
        const result = await fetch(`${import.meta.env.VITE_APP_API_URL}/invoice`, {
            method: "GET",
        });
        const arrayData = await result.json();
    }

    //Adding the Variable here potentially like
    const invoiceData = [];
    invoiceData = arrayData;
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • You can't do this. You could declare a global variable with `let`, assign the value inside the function and use the variable outside the function. Remember to only use the variable after the async function finished. – jabaa Aug 23 '22 at 14:17
  • 1
    [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321) – VLAZ Aug 23 '22 at 14:17
  • Don't access async data like that. You should return the data from the async function and either `.then()` it or `await` it so that you don't get timing issues. – zero298 Aug 23 '22 at 14:19
  • You didn't call `recieveData`, but even if you did, it would return a promise. You cannot hope to get a result *now* that is only available in some *future*. – trincot Aug 23 '22 at 14:20

0 Answers0