I created a react app that dies the following.
- Load CSV.
- Convert the CSV to JSON.
- Convert the JSON to HTML Table.
- 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]);