Home > database >  How to visualize a time series in react with hooks
How to visualize a time series in react with hooks

Time:02-09

I went through different tutorials on how to show a simple time series on React. Most of them don't use hook, so I tried to adapt the code. I got stuck when tried to retrieve data with Axios from an open API. The error I got are ERROR in ./src/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js) and ERROR in src/App.js Line 27: Parsing error: Unexpected token, expected "," (27:0)

I am encountered these errors even before to try to show something. It seems something linked with the axios.get or there is something wrong with my useEffect hook. Could you please help me with this? Many thanks

import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {
  
  useEffect(() => {
    let x = [];
    let y = [];
        
    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json').then(response=>{
      console.log('response',response)
      response.map(each => {
      x.push(each.date_of_interest)
      y.push(each.case_count)
   
      .catch((error) => {console.log(error)})
        }, [])
 
     
  
    return (
      <div>Hello </div>
    )}

export default App;

CodePudding user response:

loop on response.data:

import React, { useEffect } from "react";
import axios from "axios";

export default function App() {
  useEffect(() => {
    let x = [];
    let y = [];

    axios
      .get("https://data.cityofnewyork.us/resource/rc75-m7u3.json")
      .then((response) => {
        response.data.forEach((each) => {
          x.push(each.date_of_interest);
          y.push(each.case_count);
        });
      })
      .catch((err) => console.log(err));
  }, []);

  return <div>Hello </div>;
}

Demo

CodePudding user response:

You have several issues here:

  1. There are typos in your code - you're missing a closing }); after pushing your data
  2. You need to use an additional 'state' hook in order to access your data outside the effect function.
  3. You need to parse your response as json, after fetching it.
  4. You need to iterate over the data inside the render function in order to print it:
import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {
  const [xCoord, setXCoord] = useState([]);
  const [yCoord, setYCoord] = useState([]);
  
  useEffect(() => {
    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json')
      .then(response=> response.json())
      .then(data => {
        setXCoords(data.date_of_interest);
        setYCoords(data.case_count);
      }).catch((error) => {console.log(error)})
  }, [])
 
     
  
    return (
      <div>Hello </div>
      <pre>
         { xCoords.map(x => <span>{x}</span>) }
      </pre>
    )}

export default App;
  •  Tags:  
  • Related