Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Jest How to wait until useEffect has run?

I have the following code:

const doSomething = useCallback(someFunction);

useEffect(() => {
  // doSomething takes in the data and invokes the callback at the end as newData
  doSomething(data, (newData: string) => {
    setData(newData);
  });
}, [data, doSomething]);

When I want to test this, it only works when I use setTimeout with 1 or more ms. I suppose this is because the function in useEffect has not run yet and thus has not updated the component, correct me if I'm wrong. How can I work around this without setTimeout? Or do I need a completely different approach? Help is appreciated.

like image 235
Starfish Avatar asked May 07 '26 16:05

Starfish


1 Answers

maybe try a wrapper function, for example:

async function handleSomething(){
    const res = await doSomthing()
    setData(res)
}

then call this function inside useEffect.

like image 137
Hen Moshe Avatar answered May 10 '26 06:05

Hen Moshe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!