If condition inside the useEffect isn’t working

  Kiến thức lập trình
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.

New contributor

Kunal Chaudhary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT