score:0

you can use a useeffect hook to close drawer after a timeout.

const allanchors = ['left', 'right', 'top', 'bottom'];
for(let anchor of allanchors) {
  useeffect(() => {
    if (state[anchor]) {
      settimeout(() => {
        toggledrawer(anchor, false)()
      }, 2000); // close after 2000ms
    }
  }, [state[anchor]]);
}

i saw you're using anchor variable, hinting that you might have multiple directions for drawer. if that's not the case, you can modify code and remove the for-loop entirely.

here's a working example

const { usestate, useeffect } = react;
const { drawer, button } = materialui;

const app = (props) => {
  const [ state, setstate ] = usestate({});
  const allanchors = [ 'left', 'right', 'top', 'bottom' ];
  
  for(let anchor of allanchors) {
    useeffect(() => {
      if (state[anchor]) {
        settimeout(() => {
          toggledrawer(anchor, false)()
        }, 2000); // close after 2000ms
      }
    }, [state[anchor]]);
  }

   const toggledrawer = (anchor, open, data) => (event) => {
    if (
      // check if event is not undefined
      event &&
      event.type === "keydown" &&
      (event.key === "tab" || event.key === "shift")
    ) {
      return addproduct(data);
    }
    
    if( typeof open === 'undefined') open = !state[anchor]

    setstate(s => ({ ...s, [anchor]: open }));
  };

  return (
  <div>
  { allanchors.map(anchor =>
    (
      <react.fragment>
        <button onclick={toggledrawer(anchor)} >
          {anchor}
        </button>
        <drawer
          anchor={anchor}
          open={state[anchor]}
          onclose={toggledrawer(anchor, false)}
        >
          this is drawer
        </drawer>
      </react.fragment>
    ))
  }
  </div>
  )
}

reactdom.render(<app />, document.queryselector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@4.12.1/umd/material-ui.development.js"></script>
<div id="root" />


Related Query

More Query from same tag