Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
MATERIAL UI MENU ITEM performs action on page load

I have an onClick event listener on a Menu Item in material UI, MUI.

When I load the page, the onclick calls itself automatically. How can I fix this?

const [anchorEl, setAnchorEl] = useState(null)
  const open = Boolean(anchorEl)
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget)
  }
  const handleClose = () => {
    setAnchorEl(null)
  }


  const handleDelete = async (postId, token) => {
    setLoading(true)

    const deleted = await deletePost(postId, token)

    if (deleted) {
      setLoading(false)
      toast.success(`Post deleted successfully`)
      history.push('/feed')
      handleClose()
    } else {
      toast.error('Something went wrong')
      setLoading(false)
      handleClose()
    }
  }


<IconButton
          id='demo-positioned-button'
          aria-controls={open ? 'demo-positioned-menu' : undefined}
          aria-haspopup='true'
          aria-expanded={open ? 'true' : undefined}
          onClick={handleClick}
        >
          <MoreVertIcon sx={{ color: '#E4E4E4' }} />
        </IconButton>
<Menu 
id='demo-positioned-menu'
          aria-labelledby='demo-positioned-button'
          anchorEl={anchorEl}
          open={open}
          onClose={handleClose}
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'left',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'left',
          }}
>
 <MenuItem onClick={handleDelete(post._id, auth.token)}>
   <ListItemIcon>
     <DeleteIcon fontSize='small' />
   </ListItemIcon>
   <ListItemText>Delete</ListItemText>
 </MenuItem>

 </Menu>

When I load the page, the delete is called automatially and it repeats continuously, (Infinite loop) I have to reload the page.

I tried with simple window.alert('Hello')

It also alerts infinitely until i reload the page.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's happening because you are calling the handleDelete directly.

<MenuItem onClick={() => handleDelete(post._id, auth.token)}>
   <ListItemIcon>
     <DeleteIcon fontSize='small' />
   </ListItemIcon>
   <ListItemText>Delete</ListItemText>
 </MenuItem>

Replace handleDelete(post._id, auth.token) with () => handleDelete(post._id, auth.token)

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to call the handleDelete in an arrow function:

onClick={() => handleDelete(id)}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda