const [formData, setFormdata] = useState({});
path = "abc" // path is a string passed as prop
useEffect(() => {
// console.log('Table component rendered');
if (formData[path] === undefined) {
serviceProvider(
ctx,
uischemaData,
{
event: { _reactName: "onLoad" },
path,
...uischemaData.additionalData,
}
).then((res: any) => {
const fetchedData = res[path]?.map((e) => {
return e;
});
setFormdata((pre) => {
return {
...pre,
[path]: fetchedData,
};
});
setTableData(fetchedData || []);
});
}
I want to call the function name serviceProvider when formData[path] === undefined and when the component mounts, but the problem is when the formData[path] equals to undefined(checked on debugger) then it does not go inside the if condition.How’s that even possible?
Basically this useEffect calls an API through the serviceProvider function on component(Table) mount and res is stored in the formData, so another time the same table is rendered then it does not need to call the API again.
2
Answers
The below code snippet works, please check:
The above code snippet is pretty straightforward implementation of the code provided in the question.
Please check your implementation of the function serviceProvider.