Learning by coding, here i have simple graph, where are different datas such as current, all and filtered data, first code works fine, but i wanted to setState so i changed code a little (second code), if i uncomment 'setTest' it give 'Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.' is there a fix to this or should i somehow use useEffect? and another question is why should i call function 'kk()', and not just reference to it 'kk' because when i use reference it give error 'Uncaught TypeError: Cannot read properties of undefined' but when calling function it wont give error, but then i have used reference to function without problem 'onClickNode={onClickNode}' .
1:
import { Graph } from "react-d3-graph";
<Graph data={
hideData ?
curentData ? allData : filteredData
: allData }
onClickNode={onClickNode}
/>
2:
import { Graph } from "react-d3-graph";
const [test, setTest] = useState<any>("testData1");
const kk = () => {
// setTest("testData2")
return curentData ? allData : filteredData;
};
<Graph
data={hideData ? kk() : allData} onClickNode={onClickNode}
/>
English is not my mother language so could be mistakes.
You should not call a state changing function within your rendering logic without some sort of condition. Without a condition to prevent a state change results in an infinite loop as you are seeing.
One option you can try is call setTest("testData2") on a particular user action, like this:
const [test, setTest] = useState<any>("testData1");
const kk = () => {
return curentData ? allData : filteredData;
};
const onClickNode = () => {
// Handle other click logic...
setTest("testData2");
};
<Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />
But without seeing more of that code, that option may not make sense for you.
Another option would be to check the value of test before calling setTest("testData2"), like this:
const [test, setTest] = useState<any>("testData1");
const kk = () => {
if (test !== "testData2") {
setTest("testData2");
}
return curentData ? allData : filteredData;
};
<Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />