0

I'm trying to build a super basic UI for visualizing a live data stream using React and Javascript. I'm very new to both Javascript and React so I'm sure the issue is something basic that I am overlooking.

I want to reuse the same React component on the main page. I have a custom scatter plot chart built using the react-chartjs2 library. When I was only displaying one instance of the chart everything worked perfectly but now that there are two charts they seem to be two instances of the second instantiation and I can't figure out why.

RadarScatter.js Code:

export function RadarScatter(props) {
  const [count, setCount] = useState(0);
  const [radarData, setRadarData] = useState(defaultData);

  async function updateData() {
    let dataServerAddr = "http://127.0.0.1:5000/foghorn.api";
    let cur_time_ms = Date.now();
    let fetch_str = dataServerAddr + "/RADAR/" + props.ID + "/" + String(cur_time_ms);
    console.log(fetch_str);
    const response = await fetch(fetch_str);
    
    //FIXME Handle bad response
    const blob = await response.json();
    let graphData = {
      datasets: [
        {
          label: "Radar" + props.ID,
          data: blob.data.pc.map((el) => ({x: -el.range*Math.sin(el.azimuth), y: el.range*Math.cos(el.azimuth)})),
          backgroundColor: 'rgba(255, 99, 99, 1)',
        },
      ],
    };
    setRadarData(graphData);
  }

  useEffect(() => {
    const updateTimer = setInterval(()=>{
      setCount((oldVal)=>{
        updateData();
        return (oldVal+1);
      });
    }, 250);
    return () => {
      clearInterval(updateTimer);
    }
  }, []);

  options.plugins.title.text = "Radar " + props.ID

  return (
    <div>
      <Scatter options={options} data={radarData} />
    </div>
  );
}

App.js Code:

function App() {
  return (
    <div className="App">
      <h1>Top Down Radar FOV</h1>
      <RadarScatter ID="100:101:102:103:104:105"/>
      <RadarScatter ID="200:201:202:203:204:205"/>
    </div>
  );
}

I've read both of these stackoverflow posts.

The solution in both of these questions was to add some unique state to each instance so that they can be identified by the parent. Don't I already have that with my ID value being different for each instances of <RadarScatter/>?

When viewing the console output it appears as though the component function is being called 4 times total. The first two times are with the first ID value and the second two times are with the second ID value. This doesn't make any sense to me. Why is the function not called once with each set of props?

I've also tried using the <Fragments></Fragments> container from another link that I read but that didn't seem to have any impact either.

If anyone can explain not just how to fix my duplicate UI issue but also what is happening to cause it I would really appreciate it.

Wired365
  • 199
  • 1
  • 13

0 Answers0