Home > Blockchain >  Why isn't the updated state returned to my component?
Why isn't the updated state returned to my component?

Time:04-24

I have a drawer for my mobile navigation, It opens fine, and closes fine when I tap the drawer icon. But I'm trying to implement a tap/click off to close the navbar. So when the user clicks or taps off of the navbar it should close. But I'm getting errors for tapping off when the drawer is closed because the ref is missing from the page. So I would like to use a check to see if the drawer is open by running if (drawerIsOpen) { do...} else { dont...} Whats odd is I'm not receiving the updated state from my props. The drawer closes and opens as it should but when I console.log(drawerIsOpen) It never gives the correct state. The code below should explain some of what I'm getting at.

const Drawer = ({ drawerIsOpen, handleDrawer, drawerButtonRef }) => {
  const drawerRef = useRef(null);

  function handleClickOutside(event) {
    if (!drawerIsOpen) {
      // always returns since state is always telling me the drawer is closed
      return;
    }
    if (drawerRef.current.contains(event.target)) {
      console.log('inside');
    } else {
      console.log('outside');
      console.log(handleDrawer);
      handleDrawer();
    }
}
useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('touchstart', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, []);

My state is being sent through props. My state begins in this component:

const drawerButtonRef = useRef(null);

const [drawerIsOpen, setDrawerIsOpen] = useState(false);
const handleDrawer = () => {
    setDrawerIsOpen((prevState) => !prevState);
};

return (
  <>
    <Drawer
        drawerIsOpen={drawerIsOpen}
        handleDrawer={handleDrawer}
        drawerButtonRef={drawerButtonRef}
     />
  </>
)

CodePudding user response:

Try passing drawerIsOpen as a dependency. Your useEffect logic was being called only once.

Try the below:

useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('touchstart', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [drawerIsOpen]);

drawerRef would also need to be added to the element that you want this behavior on, otherwise its meaningless to have in your logic.

Also Drawer has no JSX element..... maybe you forgot to share in the post ?

You can also simplify this

const handleDrawer = () => {
    setDrawerIsOpen((prevState) => !prevState);
};

To this

const handleDrawer = () => {
    setDrawerIsOpen(!drawerIsOpen);
};
  • Related