Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data.

The Following Works: It displays console entries with three to-do items:

 fetch('http://localhost:3000/api/todos')
    .then(data => data.json())
    .then(success => console.log(success));

The Following Does Not Work:

fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => JSON.parse(success));

Despite my best efforts, when attempting to access success, it does not contain any data.

Console.log has been tested and is working properly.

I have also tried the following code snippet which works:

fetch('http://localhost:3000/api/todos')
    .then(res => res.json())
    .then(data => {
        let output = '';
        data.forEach(function (todo) {
        output += `
            <ul>
                <li>ID: ${todo.id}</li>
                <li>Title: ${todo.title}</li>
                <li>IsDone: ${todo.isdone}</li>
            </ul>
            `;
        });
        document.getElementById('ToDoList').innerHTML = output;
        return output;
    })
    .catch(err => console.log('Something went wrong: ', err));

However, manually updating inner HTML is not ideal; rather I need the object for other UX functionalities.

Answer №1

Another approach is to incorporate a function similar to the one demonstrated below:

 function handleResponse(response){
   //perform actions as needed
 }

 fetch('http://localhost:3000/api/data')
    .then(data => data.json())
    .then(response => handleResponse(response));

Answer №2

To store the fetched data, you can create a variable and assign the result to it as shown below:

let myData;

fetch('http://localhost:3000/api/data')
    .then(response => response.json())
    .then(data => myData = data);

You can now use the myData variable as your JavaScript object for further manipulation.

Answer №3

Below is an example of how to utilize async await:

async function getData() {
  let result = await fetch('http://localhost:3000/api/data')
  console.log(result)
}

getData()

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

I encountered an issue when trying to include the dotenv file, receiving the following error message: [TypeError: Network request failed]

babel.config.js File plugins: [ ["module:react-native-dotenv", { "envName": "APP_ENV", "moduleName": "@env", "path": ".env", "blocklist": null, "allowlist": null, "blacklist": null, // DEPRECATED "whitelist": ...

What sets the Event and EventHandler apart from each other in terms of functionality?

I am posting this question to gain clarity on the fundamental distinctions and practical applications of the Event versus EvenHandler. ...

Creating a custom script for a search field that retrieves information from an XML document

Attempting to create a script that iterates through an XML file, the provided code currently displays alerts but fails to show information when a valid value is entered into the search field. However, upon removing the error checks and keeping the final ...

Enhance your MongoDB with the power of JQuery and ExpressJS combined with the magic

I've successfully implemented a delete function using type: 'DELETE', and now I'm attempting to create an UPDATE function. However, I'm unsure if I'm approaching this correctly. Here's the code I've written so far: ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Looking for a way to automatically update your JavaScript code on your Minecraft (Bukkit)

One of my clients has requested a website design that includes a player display for each server, updating every five seconds. I'm not sure where to start with this task. Below is an example for reference. Any guidance on how to achieve this would be g ...

Utilizing AngularJS to selectively filter objects based on specific fields using the OR operator

My collection includes various items with different attributes. For instance, here is the information for one item: {"id":7,"name":"ItemName","status":"Active","statusFrom":"2016-01-04T00:00:00","development":"Started","devStartedFrom":"2016-01-04T00:00:0 ...

Merging and collaborating on a variety of JSON documents

I have limited experience working with JSON files and I'm facing some challenges. The software I'm using generates a separate JSON file for each image it processes, resulting in hundreds of individual JSON files at any given time. My main struggl ...

Calling Ajax in JavaScript

Trying to fetch a value in JavaScript using an Ajax Call, The code being used is as follows: <script> var value = $.ajax({ type:"GET", url:"get_result.php", data:"{'abc':" + $abc + "}", }); alert(val ...

The submit button in Angularjs does not respond to the Enter key press

Click below to submit: <input type="submit" ng-click="Showdata()" class="btn blue pull-right" Text="" /> Email input field: <input type="text" ng-model="texttype" class="form-control" ng-class="eml" placeholder="Enter Email" /> Password ...

Using Plotly.js within a deleted Vue.js component may result in displaying an incorrect chart

Issue I am facing a problem with deleting one of the components that contains a chart. Even after deleting the component, the chart remains visible. To see an example, check out this jsfiddle: https://jsfiddle.net/m4ywp5fc/4/ Solution Attempted I attem ...

Retrieve Wikipedia API JSON information using jQuery

$('#searchButton').click(function(){ var searchInput = ""; searchInput = document.getElementById('test'); if(searchInput.value !== ""){ $.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format ...

Tips for saving the status of an accordion controlled by an angular directive

I am currently utilizing the accordion directive from angular-bootstrap. My goal is to save the is-open attribute of this accordion, so that when users navigate to another page on the website, the state of the accordion (i.e. is-open) remains unchanged. ...

A beginner's guide to crafting a knex query with MySQL language

Within MySQL Workbench, I currently have the following code: USE my_db; SELECT transactions.created_at, price FROM transactions JOIN transactions_items ON transactions.id = transactions_items.transaction_id JOIN store_items ...

How can I resolve the issue of a lengthy link spanning two lines in Internet Explorer, while displaying correctly in other browsers on a Bootstrap navigation

Currently in the process of developing a responsive website with Bootstrap. The navigation buttons at the top are displaying correctly in Chrome, Safari, and Firefox, but in IE, the button labeled "Public Consultation" is wrapping onto two lines. I suspec ...

Unable to reach a variable within the class itself

I'm facing an issue with my MobX store. In my Store class, when I try to access this.user.permits.db, I get an error stating that this.user is undefined. I am confused as to why I can't access the @observable user. src/ui/store/store.js file: ...

Basic PHP and JSON

Encountering a frustrating issue with my script. It runs smoothly on both my local server and test server, but when I try it on the Rackspace server, it fails to execute correctly. <?php $path = "http://query.yahooapis.com/v1/public/yql?q="; $path .= ...

An exploration into effectively transforming a JSON object into a pandas dataframe with an integer-based id column using Python

I have successfully loaded the following JSON object: { "kind": "youtube#videoCategoryListResponse", "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/S730Ilt-Fi-emsQJvJAAShlR6hM\"", "items": [ ...

Transferring data only once specific agreements have been fulfilled

Imagine having a file with specific promises that, when executed sequentially, create an input file called input.txt. // prepareInput.js var step1 = function() { var promise = new Promise(function(resolve, reject) { ... }); return p ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...