daggett
daggett

Reputation: 279

Can't assign API data from fetch to variable in function

I have a JS module that is a function that fetches Issue data from our company Github, that I then want assigned to a variable:

import { request } from "https://cdn.skypack.dev/@octokit/request";

let issueData

async function getIssues() {
    const issueAPI = await request("GET repos/{owner}/{repo}/issues", {
        baseUrl: "https://company.com/api/v3/",
        owner: "me",
        repo: "exampleRepo",
    });

    window.issueData = issueAPI.data
    return issueAPI.data
}

export { getIssues, issueData }

I can't seem to get the issueAPI.data to assign to my variable issueData? What's going wrong here? I have a feeling it's something to do with the promises/async or scope but just can't work it out.

Upvotes: 1

Views: 767

Answers (1)

eloyra
eloyra

Reputation: 529

You are assigning issueAPI.data to a window variable called issueData, which is not the same variable that you have defined with let on your snippet. If you want to assign to your declared variable, you just need to do this.

let issueData = await getIssues()

If there are no other errors in the function, this should correctly assign what you want to your declared variable.

Also you can drop the window.issueData = issueAPI.data unless you really want to have that accesible from the window object.

EDIT: As Jeremy points out, this would require top-level await. A workaround also provided by Jeremy:

let issueData
( async () => { issueData = await getIssues() })()

Upvotes: 3

Related Questions