简体   繁体   中英

How to seperate keys and values from a json and store it in a array using useState hook in react

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);
      });
  }, []);

I have tried the above code..it says cases,recovered and deaths are undefined

API used: click here to see the api I want it like this..Please help: :)

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

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

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

Thank you!

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

JSON.stringify returns a string..Inorder to store it in array format we will have to use JSON.parse which returns an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM