0

When I execute setState in class component, I can pass the callback to the last argument, and callback execute after changing State:

this.setState({}, () => { *execute after changing state* })

My example:

const foo = () => {
   setOpen(false); 
   bar(); // this function should be performed after completion setOpen changing, but setOpen is async func
}

Question: How to execute bar () immediately after the update of the hook through setOpen is completed with the false argument?

2 Answers 2

2

You'd do it like this:

const [ isOpen, setIsOpen ] = useState( false );

useEffect(() => {

    if( !isOpen ) {

         bar();

    }

}, [ isOpen ]);

The useEffect hook is triggered once a change to isOpen is detected because it is listed in the dependencies for the useEffect hook.

Sign up to request clarification or add additional context in comments.

6 Comments

But bar() will execute after first render, I need execute bar() after few isOpen changes
What do you mean "a few"?
@Enkei can you provide more information on what you want? This solution will run bar() every time isOpen changes to false.
@BarryMichaelDoyle. isOpen hook is responsible for open Material-UI Dialog window. bar() is unmount Dialog component from parent component. I need to close dialog window by isOpen hook with default animations, and then unmount this component by bar() function
@BarryMichaelDoyle so, if I will use this answer, my dialog window component with isOpen = false will render, and then bar() will executed, and component unmount
|
-1

From what I've gathered, you're dealing with some animations upon your component closing and that bar is the function to unmount the component.

Technically what you'd be looking for (if the animation takes 500ms to complete) is this:

// Add this line somewhere outside of your component, preferably in a helpers file.
const delay = ms => new Promise(res => setTimeout(res, ms));

const foo = async () => {
   setOpen(false);
   await delay(500) // Change this value to match the animation time
   bar();
}

This should allow your animation to ru before unmounting the component.

1 Comment

What do you suggest? How is it a dirty hack? If the OP has a CSS animation that's animating the component closing and then he wants to unmount it. How else would you wait for the CSS animation to complete before unkounting?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.