What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand?

async function fetchData() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
  let data = await response.json();
}

fetchData();

data.forEach((item) => {
  item.forEach((nestedItem) => {
    placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid);
    placeRandomCharacter("O", enemyGrid, enemyGridSize);
    drawBreak();
  });

Answer №1

Due to the scoping of shipsJSON within the githubUsers function, one solution could be to use await on the returned data in another async function and then iterate through it.

async function githubUsers() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
  return response.json();
}

async function main() {
  const shipsJSON = await githubUsers();
  // write the remaining code here
}

main();

Another approach is possible since fetch returns a promise:

function githubUsers() {
  return fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
}

async function main() {
  const response = await githubUsers();
  const shipsJSON = await response.json();
  // write the remaining code here
}

main();

Answer №2

When using async function, the githubUsers call may not complete before your foreach loop. Additionally, the shipsJSON variable is declared within the scope of githubUsers, making it unavailable outside of it. To access it in the outer scope, you should use return. Here's how you can do it:

async function githubUsers() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d')
  return response.json()
}

async function fetchAndLoop() {
    const json = await githubUsers()

    json.forEach((item) => {
      item.forEach((nestedItem) => {
        placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid)
        // placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid);
        placeRandomCharacter('O', enemyGrid, enemyGridSize);
        drawBreak();

      });
}

fetchAndLoop();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting various data points from a JSON document

I am dealing with a JSON file containing multiple elements like the following: { "code" : "hfuiew89", "type" : "location", "coordinates" : [ { "lat" : 40.9861, "lon" : 29.1046, "index" : 1 }, { "lat" : 40.9976, "lon" : 29.1153, "index" : 2 } ...

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

Is there a way to determine if a file is an audio or video file using Vue.js by examining its URL?

I am currently working on a Vuetify playlist that contains a mix of audio and video media files. My goal is to create functionality that allows me to launch a video player if the file is a video, or utilize the html5 audio component for .mp3 files: ...

Separate the keys and values of a JSON file into individual rows within a pandas dataframe

Looking to extract keys and values from JSON into separate rows in pandas The current structure is: |---------------------|------------------| | session | scoring | |---------------------|------------------| | session1 | {i ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Utilizing API data to set the state in a React component

In my quest to modify the state of this React component, I have a variable called rankAndTeam that holds the "prints=>" data listed below. My goal is to assign "Washington Capitals" to this.state.teamRank["0"], "New York Islanders" to this.state.teamRank[" ...

Why isn't the function in my React child component passing its parameters to the parent component's function as expected?

In the parent: const [currentPinPosition, setCurrentPinPosition] = React.useState({ lat: 0 , lng: 0 }); const updateCurrentPinPos = (position) => { console.log(position); setCurrentPinPosition({ lat: position.lat, lng: position.lng }); }; / ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...

Add a message displaying the error in the input field using jQuery Validation

Is there a way to append the jQuery Validation error messages to the input field or get help with positioning them properly? The random popping up of error messages is causing chaos in the form layout. I prefer to have the error messages displayed undern ...

How do I submit my form data as a JSON object using AngularJS?

I'm currently in the process of developing my first Angular app and trying to incorporate form submission into JSON data. Below is the form I have created: <span ng-show="show"> <form name="inputForm" class="form-group" ng-controller="For ...

What are some ways to enhance the speed of my canvas animations?

My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly. Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive? What would be ...

Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious. JS const gri ...

Tips for utilizing jquery.load for fetching a section of an html document or an entire html file

I'm experimenting with jquery's load function to dynamically fetch and display HTML content, rather than using $.ajax(). I enjoy exploring the various features that jQuery offers and want to understand how each one works. Below is the code I am ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

Enhance JSON nesting with knockoutJS

I am currently working on updating a JSON object in memory using the knockout.js user interface. However, I have encountered an issue where changes made in the UI do not seem to reflect on the JSON data itself. To troubleshoot this problem, I have added bu ...

Unraveling the Json Object with php and angularJs

When transmitting data from AngularJS as JSON, it arrives in the following format: {data: "stdClass Object↵(↵[0] => B↵[vin] => vin123…[value] => Gambia↵[country_name] => Gambia↵)↵", status: 200, headers: function, config: Object} In PHP, th ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...