Is it possible to retrieve the JSON object from the Fetch API response and access it externally?

Currently, I am facing an issue accessing the variable emoji_map beyond the scope of the then function in my code and I'm unsure how to resolve it.

Below is the relevant snippet of my code:

 if (req) {
    fetch(req).then(function(response) {
        return response.json();
    }).then(function(response) {
    /* Begin observing */
    emoji_map = response.emoji_map;
    console.log(emoji_map);
    });

}

Whenever I attempt to access emoji_map outside the if loop using a console.log(), I cannot retrieve the assigned response value. Could someone assist me with this?

Answer â„–1

For a deeper understanding of JavaScript lexical scoping and closures, I recommend checking out the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures.

function initialize() {
  var fruit = "Apple"; // fruit is a local variable created by init
  function displayFruit() { // displayFruit() is the inner function, a closure
    alert(fruit); // accessing the variable declared in the parent function    
  }
  displayFruit();    
}
initialize();

The function initialize() sets up a local variable called fruit and defines an inner function called displayFruit(). This inner function can only be accessed within the body of initialize(). While displayFruit() does not have any local variables of its own, it can make use of the outer function's variables like fruit.

Answer â„–2

Why not declare a global variable outside the fetch statement and store the response in that variable? This way, you can access the response data later on.


          let responseData;          
          if (request) {
            fetch(request).then(function(response) {
               responseData = response.json();
               return response.json();
            }).then(function(response) {
                 /* Begin observing */
                 emojiData = responseData.emoji_map;
                 console.log(emojiData);
             });

          }

     OR 

      fetch('https://example.com/api/data').then(function(response) {
           return //...
        }).then(function(returnedValue) {
         // ...
       }).catch(function(error) {
           // Handle errors here
       });

You can test out the code above or visit this link for more information.

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

In Javascript, use the replace() function to target and replace text that is not contained

Seeking help with highlighting search strings in an autocomplete form. In my current approach, I aim to encapsulate the search term within specific tags for emphasis. However, complications arise when the pattern resides within HTML tags. var searchPatter ...

Populate the input file field on page load

I have a simple HTML form that allows users to choose files. <input multiple type="file" name="file"/> <input type="submit" name="submit" value="Submit" /> When the user clicks on a specific button on the home page, they will be directed to ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Storing and securing passwords in Node/Express using hashing and salting techniques

Utilizing the Crypto module within Node's standard library is a necessity. I have established a POST route dedicated to handling a registration form: app.post('/superadmin/add-account', function(req, res) { // Creating shorthand variable ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...

Assistance in configuring Zurb Foundation 5 for optimal integration with Laravel

As a relatively new user to Laravel with previous experience using older versions of Foundation, I am currently in the process of setting up a new Laravel project. My goal is to integrate the Foundation framework into my project, but I find myself a bit co ...

The properly grouped image failed to load

I have a React component designed to showcase an image, with Webpack handling the bundling process. It's important to mention that I am utilizing ReactJS.NET in this scenario. Even though the webpack bundle is successfully generated and the .jpg fil ...

Guide to inserting an HTML file into an article's content

After downloading an extension from freefrontedit and uploading it to my server in the directory /accordeon, I successfully accessed it by pointing my browser to . However, I am now faced with the challenge of loading the index.html into my Joomla article ...

comparing jquery version 1 and jquery version 3 backward-compatible browsers

It has come to my attention that jquery 2.x does not offer support for legacy browsers. If I wish to accommodate those outdated Internet Explorer versions, I must resort to using jquery 1.x. However, I am curious about jquery 3.x. Does it provide support ...

Refresh my website's specific table automatically whenever the database is updated. Alternatively, reload the table every 2 seconds to ensure the latest values from the database are displayed

How can I update table values in real-time when the database in phpMyAdmin is updated? I have implemented some code that successfully updates the data on my webpage, but the issue is that the entire page reloads every 2 seconds. Is there a way to only ...

Creating a default menu within a specific route in Ember.js is a crucial step in

I have created a JSBin code for my Ember.js application which can be found here: When I click on Item A, I want the ABCD menu on the left to remain visible and not disappear. Thank you. ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item. const array = [ {India: { Score: '12', PlayedMatched: '21' } }, { China: { Score: '52', PlayedMatched: '51 ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

Add a Filter to the Observer (__ob__) in Typescript

I am trying to implement a filter using this.Grid.option("dataSource").filter(x => x.Placeholder != null) however, it doesn't seem to be working when I run console.log(this.Grid.option("dataSource")); I receive (72) [{…}, {…}, {…}, {†...

Add an item to an array and then transform the array into a JSON format

I have a situation where I am creating an object and pushing it into an array. After that, I convert it into JSON format. When I display the dataCharts using an alert, it is returned in this form: [{"AllLinks":"Link9","LinkURL":"url1"},{"AllLinks":"Link6" ...

Ways to standardize the input email address?

While using express-validator, I came across an issue where I used normalize email for validation of email during sign up and stored the normalized email on the server. Validation code: router.post( "/signup", [ check("name").n ...

What is the best way to input variables into json values? [JavaScript]

let countryCode; let countryName; $(window).on("load", function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" }).done(function (json) { countryCode = json.country_code; $(function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" ...

The property fails to reflect changes in state

I am currently developing an application that requires fetching data asynchronously and preserving the state in the parent component while also passing the data reference to children components. I encountered an issue where the props do not update when the ...

The functionality to organize items appears to be malfunctioning. (Javascript)

I want to add a price sorting feature that allows users to sort by either 'high to low' or 'low to high' using a drop-down menu. The products I want to sort are the w3-containers, each representing a different product. However, nothin ...