简体   繁体   中英

Add object array to setState

I'm trying to add an object array in the state series. With this code the useEffect function get stuck in an infinite loop. How can I solve this? Without adding the series const as parameter I get the error about a missing dependency and the code will only run on startup.

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

const LineChart = () => {
  const [series, setSeries] = useState([]);

  useEffect(() => {
    const url = "http://localhost:4000";

    const fetchData = async () => {
      try {

        fetch(url, {
          method: "GET",
        })
          .then((response) => response.json())
          .then((data) => {
            let chartData = data.testRunSummaries
              .map(function (testrun) {
                return {
                  duration: testrun.endTime - testrun.startTime,
                  label: testrun.testSetName + "#" + testrun.userFacingId,
                  testrun: testrun.testRunId,
                  status: testrun.status,
                };
              });
            setSeries(chartData, ...series);
            console.log(series);

          });
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, [series]);

  return (
   ...
  );
};

export default LineChart;

series is in your useEffect dependency array. And your useEffect is changing series . So obviously you'll be stuck in a infinite loop.

You don't need your series to be set as a dependency for useEffect . As your useEffect will only be trigger once on mount, you can just have

setSeries(chartData);

And if you really need to have former values of series , you should use

setSeries(series => [...chartData, ...series]);

Moreover, seeing your

setSeries(chartData, ...series);
console.log(series);

Let me remind you that setState is async there is no way this will log your updated state:)

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