I was trying to control a Material-UI drawer by using RTK status, this is my component:

export default function NavToolbar(props) {
  const dispatch = useDispatch();
  const nodeDrawerOpened = useSelector(
    state => state.componentStatus.leftDrawerOpened
  );
  const nodeDrawerOpenHandler = (status)=> {
    dispatch(setLeftDrawerOpen(!status));
  };

  return (
    <>
      <Box variant="" className={styles.cntrToolBar}>
        <Grid
          container
          columns={24}
          direction="row"
          justifyContent="center"
          alignItems="center"
        >
          <Grid item xs={1}>
            <Box className={styles.cntrToolBarLeftTools}>
              <IconButton className={styles.toolBarIconBtn}>
                <ListIcon/>
              </IconButton>
            </Box>
          </Grid>
          <Grid item xs={20}>
            <Progressbar/>
          </Grid>
          <Grid item xs={3}>
            <Box className={styles.cntrToolBarRightTools}>
              <IconButton
                className={styles.toolBarIconBtn}
                onClick={() => nodeDrawerOpenHandler(nodeDrawerOpened)}>
                <SimCardDownloadOutlinedIcon />
              </IconButton>
            </Box>
          </Grid>
        </Grid>
      </Box>
    </>
  )
}

It didn't work as I thought.

Then I tried to remove the props for nodeDrawerOpenHandler and pass the nodeDrawerOpened directly to dispatch function and it worked well. Like this:

export default function NavToolbar(props) {

  const dispatch = useDispatch();
  const nodeDrawerOpened = useSelector(
    state => state.componentStatus.leftDrawerOpened
  );

  // **
  const nodeDrawerOpenHandler = ()=> {
    dispatch(setLeftDrawerOpen(!nodeDrawerOpened));
  };

  return (
    <>
      <Box variant="" className={styles.cntrToolBar}>
        <Grid
          container
          columns={24}
          direction="row"
          justifyContent="center"
          alignItems="center"
        >
          <Grid item xs={1}>
            <Box className={styles.cntrToolBarLeftTools}>
              <IconButton className={styles.toolBarIconBtn}>
                <ListIcon/>
              </IconButton>
            </Box>
          </Grid>
          <Grid item xs={20}>
            <Progressbar/>
          </Grid>
          <Grid item xs={3}>
            <Box className={styles.cntrToolBarRightTools}>
              <IconButton
                className={styles.toolBarIconBtn}
                onClick={() => nodeDrawerOpenHandler()}> // **
                <SimCardDownloadOutlinedIcon />
              </IconButton>
            </Box>
          </Grid>
        </Grid>
      </Box>
    </>
  )
}

I know the status from redux are rendered asynchronously, but what is the theory behind my example? Can someone explain this to me with some details? What is the difference of these two ways?

0

There are 0 best solutions below