zhyp
zhyp

Reputation: 329

ReactJS - Charts from ChartJS re-rendering after first page load

I'm currently on a project that the use of charts is needed, so I opted for chartsjs, but I'm facing a small problem that have two parts. enter image description here

  1. When the page first loads my data is not being shown, and some graphs/data appear as undefined (I know that how it should work when I set some object like this “obj?.smt”), and I don't know if there's a way to mask it until the loading is done.

  2. As you can see on the GIF whenever there's a reload on the page the graphs kinda flicker, and it kinda worries me, this page is going to have at least 50 graphs (not my idea), so if it's flickering does it mean that it's rendering 2 times? Or even more under the hood?

useEffect(() => {
    const fetchDreData = async () => {
      try {
        const res = await http.get("/endpoint1");
        const data = await res.data;
        const final = data.data;
        // console.log(final);
        setEstimatedMonths(final);
      } catch (e) {
        console.log("error", e);
      }
    };
    const fetchProductsData = async () => {
      try {
        const res = await http.get("/endpoint2");
        const data = await res.data;
        const final = data.data;
        // console.log(res);
        setEstimatedProducts(final);
      } catch (e) {
        console.log("error", e);
      }
    };
    fetchDreData();
    fetchProductsData();
  }, [control]);

  useEffect(() => {
    flatData();
  }, [estimatedProducts, estimatedMonths]);

  useLayoutEffect(() => {
    chart();
  }, [values]);

Quickly explaining what's happening over here. On the first useEffect there are 2 calls to different endpoints and the data from it is being set on two separate states. On the 2º one where flatData() is being called, some data from the 2 states are being manipulated because whoever did the backend decided that some stuff should be calculated on the front. And the last one is a big object where Data from everywhere comes together, is set in the graphs.

I don't know if those are being caused by some dumb mistake that I'm making, or it's just how ChartJS behaves.

Upvotes: 0

Views: 1585

Answers (1)

Aleksandr Smyshliaev
Aleksandr Smyshliaev

Reputation: 420

You can put console.log or console.count to see how it executed.

My guess is that flatData called twice, when value of estimatedProducts changes and when value of estimatedMonths changes. If values come from there so first component doesn't have data, after one API call finished it set one state and update, on second API call it updates again.

You can combine 2 API calls in 1 function and set state 1 time.

Or put condition in useEffect

  useEffect(() => {
    if (estimatedProducts && estimatedMonths) {
      flatData();
    }
  }, [estimatedProducts, estimatedMonths]);

Upvotes: 1

Related Questions