Home > Back-end >  Unable to understand why my app is entering an infinite loop
Unable to understand why my app is entering an infinite loop

Time:04-19

I created a react app that dies the following.

  1. Load CSV.
  2. Convert the CSV to JSON.
  3. Convert the JSON to HTML Table.
  4. On the button click do some processing.

Currently, my app is working as expected, but the issue is, it is going into an infinite loop on file load. Not sure where I'm going wrong.

Here is the working code. Can someone please let me know where I'm going wrong?

Thanks

CodePudding user response:

I haven't thoroughly debugged your code, but it looks like you have an infinite loop in your useEffect. When you upload a file, that causes the ProcessData component to render, and that component has a useEffect which depends on csvArray. However, that same useEffect also modifies csvArray, which would cause it to run again. Generally, a useEffect hook should not change any state values it depends on.

Also, instead of just linking to your code, it's nice if the question itself includes a minimal code sample that reproduces your problem.

CodePudding user response:

It is going into an infinite loop on file load, because you put csvArray in useEffect's array, this means: every time csvArray changed the function fired again.

The solution:

useEffect(() => {
   processCSV(csvData);
   if (isProcessChange) {
      setCsvArray(state => {
        state.map((item) => {
          var currRowValues = Object.entries(item);
          var nd = currRowValues.reduce((a, [key, value]) => {
            if (key === "sum") {
              return a;
            }
            return a   value;
          }, 0);
          return { ...item, sum: nd };
        });
      });
    }
  }, [isProcessChange, csvData]);

And put setKeys in separate useEffect:

useEffect(() => {
   setKeys(Object.keys(csvArray.length ? csvArray[0] : {}));
}, [csvArray]);

Demo: https://codesandbox.io/s/modest-snowflake-y7ziqt

  • Related