'reactjs state is not being updated when invoked from a function

here is the context

I am invoking a function invoked(..) from another component. Inside invoked I setState but the state does not get set. It does not trigger the useEffect nor does it take the updated value in the useInterval.

Below is the code.

Component 1 = exampleComp.ts

const exampleComp = ({initValue: ExampleProps}) {
  const [params, setParams] = useState<{field1: null | string}> ({field1: null});

  const invoked = (x: string) => {
    console.log("inside invoked"); // this gets printed
    setParams({"field1": x});
  };

  useEffect(() => {
    console.log(params); // does not come here :(
  }, [params]);

  const fetchData = {...};

  useInterval(
      () => {
        if (!params.field1 || fetching) return;
        console.log("in interval", params); // does not come here too :(
        fetchData(params.field1);
      },
      params && !fetching ? 5000: null,
    );

    return {invoked, ...}
}

Component 2:

const newComp  = ({initValue: ExampleProps}) {
  const {invoked, ..} = useExampleComp({...}); //Example comp is the above component.
  useEffect(() => {
    invoked(x);
  }, []);
}

Any help will be appreciated! thanks.



Solution 1:[1]

Turns out that the component was unmounting too early. This happens when the scope of the component is too narrow.

If you have a similar problem, try logging the component to see if this is indeed happening.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 suprita shankar