I have a function that receives JSON data from my server, I use the {jsonData.map((element) => renderComponents(element, jsonData))}
function to loop through it and send each object to
renderComponents
function along with the full JSON data, and this function has a switch statement with multiple cases for different element.componentType
(from the JSON data).
this is the switch statement
function renderComponent(element, jsonData) {
switch (element.componentType) {
case 'TypeOne':
return (
<div>
</div>
);
break;
case 'TypeTwo':
useEffect(() => {
console.log("test");
}, [jsonData]);
return (
<div>
</div>
);
break;
}
}
it works the first time it loads, but whenever I use another function to update the jsonData and add a new element of TypeTwo
I get an error before the useEffect
executes.
I can assure you the updated jsonData is fine and when I load a new TypeOne
it gets loaded perfectly, just the issue with TypeTwo
here’s the error code
Warning: React has detected a change in the order of Hooks called by MainFunction. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
Previous render Next render
------------------------------------------------------
1. useState useState
2. useEffect useEffect
3. undefined useEffect
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
this is my json
{
"title": "MY element",
"id": 3262405,
"componentType": "TypeOne",
},
{
"title": "MY element two",
"id": 9998454,
"componentType": "TypeTwo",
}
the issue is with useEffect, it doesn’t get called and the code stops right there
3
Answers
Hooks need to be used at the outermost layer of the function
Try changing your code to:
As useEffect has to be called at the top level of the functional component.
Split these components outside the primary function to avoid unnecessary rendering, I usually create a new file for each option.
There are some caveats when using hooks, they cannot be called conditionally or in a sub-function like in your sample…
more info: https://react.dev/reference/react