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.
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)
You have to call the handleDelete in an arrow function:
onClick={() => handleDelete(id)}