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

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Enhancing the visual appeal of a javascript canvas animation

I am facing a small issue and I want to incorporate an animation from: http://codepen.io/chuckeles/pen/mJeaNJ My main query is how can I modify it so that instead of dots, there would be small images? Which part of the code should I edit for this purpose? ...

Is it feasible to execute exe files within a ReactJS environment?

Hey there! I've created a Game Launcher using ReactJS for my Unity game and was wondering if it's feasible to start the game (an exe file) simply by clicking on the play button. Can anyone please advise me on this? ...

There was a problem with retrieving the data and converting it to Json format in ASP.NET

As a beginner in ASP.NET, I have recently worked on Json parsing when retrieving data in my WebAPI controller. Here is an example of how I achieved this: public JsonResult getResult() { string dataconfig = Convert.ToString(Configuratio ...

Any tips on how to retrieve my mesh that has disappeared off the screen?

Struggling to find a way to detect when an element goes off screen, can someone provide guidance? My project utilizes WebGL along with Three.js. ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

What is the best way to provide JSON data in Angular?

I am working on an Angular 4 application that is using Webpack, and I am currently facing a challenge with serving a JSON file. I have two main questions regarding this: When the JSON file is static, I am struggling to configure Webpack to handle it the ...

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

oj-select-one displays a comprehensive list of values in the dropdown

Typically, oj-select-one will only display the first 15 values before requiring the user to search for more. Is there a way to show all values in the dropdown list without needing to use the search function? I attempted to use minimumResultsForSearch as s ...

Styling the elements that are next to each other using CSS

Hey there, what if I have HTML elements structured like this: <div> <div>Name</div> <div><input type="text" class="check"> <div>Age</div> <div><input type="number" class="check"></div> ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

Having trouble displaying React Native image when attempting to load location data from a JSON file

A unique json file is used to store titles and image locations for each element. The data structure includes keys, titles, and image paths. [ {"key": "a", "title": "Bangladesh", "image": "require('./img/bangladesh.jpg')"}, {"key": "b", "title" ...

What is the interpretation of this error message and is there a solution I can apply to resolve

Utilizing the tweepy API, I am streaming specific information and saving it into a CSV. While tweets are being stored successfully, an error message keeps appearing: ('failed ondata', 'coercing to Unicode: need string or buffer, NoneType fou ...

Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method. The issue arises when attempting to make a DELETE request using axios, resulting in a Request ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

What steps can be taken to create an electron menu for easily conducting a general search within the current window?

I am searching for a solution to create an electron menu that includes the label "Find..." and performs a general search within the current browser window. While I was successful in adding the option, I am struggling to figure out how to access the browser ...

How to Handle Non-Conventional JSON Parsing in AngularJS

When retrieving a JSON response from a Restful service, the format may not always be accepted by Angular. For example: { "comments":{ "columns":[ "clientId", "treatmentDate", "comments", "photo", "pra ...

Integrating MongoDB data values with Node.js for enhanced functionality

Hey everyone, I'm looking to add two field values {type:Number} from a MongoDB collection using node js and then store the result back in the same collection. To achieve this, I have outlined the steps below: Retrieve the data value from MongoDB wit ...

Modify the readonly property of an input element in ReactJS

I am looking to manipulate attributes on an HTML input element. Here is what I have attempted: constructor(props) { super(props); this.state = {inputState: 'readOnly'}; } And within the render function: <input className="form-contr ...