Skip to content

Chart JS in React doesn’t fetch data

I’ve built a coronavirus table and whenever someone clicks on the name of the particular country modal pops up with active cases chart. I realized that it might be an issue with the Modal Component imported from Bootstrap(but not quite sure). When I set the animation to false chart doesn’t show data on every modal opening. When the animation props are not included data sometimes is not loaded. Closing and reopening a couple of times does a trick tho.

  <Modal show={show} onHide={handleClose}
        animation={false}
        size="lg"
        aria-labelledby="contained-modal-title-vcenter"
        centered />


const Chart = ({CountryName}) => {
    const[data, setData] = useState({});
    let caseDate = [];
    let active = [];
    let confirmed = [];
    let deaths = [];
    let caseDatesSubstracted = [];

    const activeChart = () => {
        setData({
            labels: caseDatesSubstracted,
            datasets: [
                {
                    label: 'Active Cases',
                    data: active,
                    backgroundColor: [
                        ['black']
                    ],
                }
            ]
        })
    }
useEffect(() => {
        const loadData = async() => {
          await fetch(`https://api.covid19api.com/total/dayone/country/${CountryName}`)
          .then(response => response.json())
          .then(data => {
            for(const dataObj of data) {
                console.log(data)
                caseDate.push(dataObj.Date);
                active.push(dataObj.Active);
                confirmed.push(dataObj.Confirmed)
                deaths.push(dataObj.Deaths)
            }
            for(let i = 0; i < caseDate.length; i++){
                caseDatesSubstracted.push(caseDate[i].substring(0, caseDate[i].length-10));
            }
          })
          }
          loadData();
          activeChart();
          confirmedChart();
          deathChart();
    }, []);

    return(
        <div className="chart">
            <h1 style={{margin: '50px 0'}}>Active Cases</h1>
            <Line
            data={data}
            />
        </div>
    )
}

Answer

try moving everything into useEffect like this. do not mix state and “let” variables.

I’m not sure what these 2 functions do, but it’s not advisable to those variables inside the function.

    confirmedChart();
    deathChart();

try these.

const Chart = ({ CountryName }) => {
  const [data, setData] = useState({});


  const activeChart = (caseDatesSubstracted) => {
        //if u want to separate, then pass in the arg.
        setData({ .... }) // now u can use caseDatesSubstracted here.
  }



  useEffect(() => {
    const loadData = async() => {
      await fetch(`https://api.covid19api.com/total/dayone/country/${CountryName}`)
        .then(response => response.json())
        .then(data => {
          //do not declare them outside useEffect as they get re-initialize on every render.
          let caseDate = [];
          let active = [];
          let confirmed = [];
          let deaths = [];
          let caseDatesSubstracted = [];

          for (const dataObj of data) {
            console.log(data)
            caseDate.push(dataObj.Date);
            active.push(dataObj.Active);
            confirmed.push(dataObj.Confirmed)
            deaths.push(dataObj.Deaths)
          }
          for (let i = 0; i < caseDate.length; i++) {
            caseDatesSubstracted.push(caseDate[i].substring(0, caseDate[i].length - 10));
          }

          //set ur state here.
          /* alternatively, use activeChart(caseDatesSubstracted) by passing in the variable */
          setData({
            labels: caseDatesSubstracted,
            datasets: [{
              label: 'Active Cases',
              data: active,
              backgroundColor: [
                ['black']
              ],
            }]
          })
        })
    }
    loadData();
    confirmedChart(); //not good, move them. follow what I did for activeChart()
    deathChart(); // not good, move them. follow what I did for activeChart()
  }, []);


}