run setState after others setStates are completed

Viewed 24
  const onDrawerClose = () => {
    setCloseDrawer1(false);
    setCloseDrawer2(false);
    setData(null);
  };

When some fields in the data are empty I show error message. It works good but when I close the sidebar, while it's closing I can see for 1second or so this error message since here in the code above we set data to null, how I can properly run the third setState after the previous two are completed?

1 Answers

You can listen when the draw1 and draw2 are closed using an useEffect like:

useEffect(() => {
   if(!closeDrawer1 && !closeDrawer2) {
       setData(null);
   }
}, [closeDrawer1, closeDrawer2])

If there is an animation when drawers are closing you can set data after the animation happen using setTimeout.

useEffect(() => {
    const drawerCloseTimeout = 1000; // 1 sec
    if(!closeDrawer1 && !closeDrawer2) {
        const timeout = setTimeout(() => setData(null), drawerCloseTimeout);
        return () => clearTimeout(timeout);
    }
}, [closeDrawer1, closeDrawer2]);
Related