A guide on extracting keys and values from a JSON object and saving them in an array with the useState hook in a React application

function Graph() {
  const [tcases, setCases] = useState([]);
  const [recovered, setRecovered] = useState([]);
  const [deaths, setDeaths] = useState([]);
  useEffect(() => {
    axios
      .get("https://disease.sh/v3/covid-19/historical/all?lastdays=all")
      .then((res) => {
        setCases(Object.values(res.data.cases));
        setRecovered(Object.values(res.data.recovered)));
        setDeaths(Object.values(res.data.deaths)));
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

The code above is showing an error stating that cases, recovered, and deaths are undefined.

For the API used, please click here to see the API. I need the data in the following format. Can someone assist me with this? :)

   tcases=[555,654,941...........]

   recovered=[17,18,26.........]

    deaths=[28,30,36...........]

Thank you!

Answer №1

function GraphComponent() {
  const [totalCases, setTotalCases] = useState([]);
  const [totalRecovered, setTotalRecovered] = useState([]);
  const [totalDeaths, setTotalDeaths] = useState([]);
  const [dates, setDates] = useState([]);
  useEffect(() => {
    axios
      .get("https://disease.sh/v3/covid-19/historical/all?lastdays=all")
      .then(res => {
        setTotalCases(JSON.parse(JSON.stringify(Object.values(res.data.cases))));
        setTotalDeaths(JSON.parse(JSON.stringify(Object.values(res.data.deaths))));
        setTotalRecovered(JSON.parse(JSON.stringify(Object.values(res.data.recovered))));
        
      })
      .catch(err => {
        console.error(err);
      });
  }, []);

When using JSON.stringify, remember it returns a string. To store it in array format, we need to use JSON.parse which returns an object.

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

Tips for identifying and handling a 400 bad request error in an HTTP response within an Angular 2 application

I attempted to handle the error 400 bad request in this manner: catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { console.log( 'err ...

Unraveling complex JSON structures in Node.js

I've been working on parsing nested JSON data and here is the code I'm currently using var str = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}'; v ...

Troubleshooting a labeling problem in a donut chart with Chart.js

$(document).ready(function(){ function call() { $.ajax({ url: "chartjs/tempdata.php", method:"GET", cache: false, success: function(data) { console.log(data); var difference=[]; var percentage=[]; var finaldata=[]; for(var i in data) { //time.push( ...

Generating a new root in React 18 results in numerous rounds of rendering and execution

Every time I attempt to run this code in React 18, it seems to render multiple times unlike React 17 where it only executes once and functions properly. How can I modify the code so that it only runs once? Is there a specific reason for the multiple execu ...

How to delete a property from a JSON object using PowerShell

I am facing a challenge with the following JSON data where I need to delete the streets from the Address array within the JSON object using PowerShell. { "Customer": [ { "id": "123" } ], "Nationality&q ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

Tips for creating a responsive layout to ensure that H2 achieves its optimal font size in a one-line DIV

Is there a way to ensure that an H2 headline fits within the width of a DIV element? I am looking for a solution where the font size of the H2 automatically adjusts to display its full text without overflowing or breaking into a second line inside the DIV ...

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Error: To activate Bootstrap's dropdowns on button groups, Popper.js must be installed and configured correctly

I utilized this code within my MVC application: <div class="btn-group" role="group"> <button id="btnGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown ...

What is the process for inserting an "inline image" in a form prior to uploading it?

I am looking to implement a feature that allows users to write a post and seamlessly upload images within the content, similar to a CMS blog post. Writing the file upload script is straightforward, but creating functionality for an "inline" image placement ...

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

The functionality for transferring ERC20 claim tokens seems to be malfunctioning

I am facing an issue with my contract while trying to execute the claimFreeToken function. Even though the contract does not have enough tokens, the function does not return an error and the token also does not get received. Can anyone point out where I ...

Using the Greasemonkey browser extension, one can employ the waitForKeyElements utility to trigger a function once a designated element becomes visible on the webpage

(In connection to the question I posted on Stack Overflow). I have been developing a userscript for metal-archives.com, which can be found here. When you navigate to a band page (like this example), you will see the DISCOGRAPHY section and its sub-tabs ...

Lately, I've been coming across mentions of "myApp.controllers" and "myApp.modules" in Angular JS. Can anyone explain the significance of these terms?

Recently, I've come across code that looks like this: angular.module('app.controllers') This pattern has appeared in a few tutorials I've read. However, the purpose of the .controllers within the module name is unclear to me. I'v ...

Retrieve the main key and its corresponding data from a cumbersome JSON file by utilizing streaming processes

As part of a system process, one step involves isolating a specific key and its corresponding value from a JSON file and saving it to a separate file for further processing in an unrelated script. An example subset of the original JSON file is as follows: ...

Using the preselection feature in the MUI DataGrid can cause the grid to become disabled

I am customizing a mui datagrid to have preselected rows using the following code snippet: const movieCrewList = movieCrew.map((item) => item.id); const [selecteTabledData, setSelectedTableData] = React.useState([]); <DataGrid rows={crewData} c ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

Having trouble including a YouTube iframe code within the document ready function

I am having trouble getting the youtube iframe API code to work properly within my $(document).ready() function. When I try to add the code inside the function, the player does not load. However, when I move the code outside of the document.ready, the play ...