How to display Material-ui Alert based on the response of axios.post reactjs

Viewed 13029

Currently, using default alert which is alert(response.data.result). To make my site more beautiful, I want to use Material-ui Alert. https://material-ui.com/components/alert/

My issue is I have no idea on how to call it from const.

Here's my code.

function Test(){
const saveData=async() => {
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          alert(response.data.result)
        }
      else
        {
          alert(response.data.result)
          //<Alert severity='error'>{response.data.result}</Alert> tried to use this but nothing displayed
          }
     }).catch(error=>{
        alert(error)
     })

//content of modal
cosnt bodyInsert = (
<div>
    ...fields
    <Button onClick={()=>saveData()}>Save</Button>
</div>
)
return(
<div>
<Modal
   open = {modalInsert}
   onClose = {openCloseModalInsert}>
   {bodyInsert}
</Modal>
</div>
)
}
export default Test;

Hoping for your consideration. thank you.

4 Answers
function Test(){
const saveData=async() => {
    const [alert, setAlert] = useState(false);
    const [alertContent, setAlertContent] = useState('');
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          setAlertContent(response.data.result);
          setAlert(true);
        }
      else
        {
          setAlertContent(response.data.result);
          setAlert(true);
        }
     }).catch(error=>{
        alert(error)
     })

//content of modal
cosnt bodyInsert = (
<div>
    ...fields
    <Button onClick={()=>saveData()}>Save</Button>
</div>
)
return(
<div>
{alert ? <Alert severity='error'>{alertContent}</Alert> : <></> }
<Modal
   open = {modalInsert}
   onClose = {openCloseModalInsert}>
   {bodyInsert}
</Modal>
</div>
)
}

I think you can not do it that way. Use a state for it.

const [showAlert, setShowAlert] = useState(null);

const saveData=async() => {
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          alert(response.data.result)
        }
      else
        {
          alert(response.data.result)
          setShowAlert(response.data.result);
        }
         
     }).catch(error=>{
        alert(error)
     })

// Your return
return showAlert && <Alert severity='error'  onClose={() => setShowAlert(null)} > { showAlert } </Alert>

You can use Collapse component collapse doc

const alertComponent = (<Alert severity='error'>{alertContent}</Alert>);

<Collapse in={alert}>{ alertComponent }</Collapse>

We can use <Alert> and <Dialog> components to create an alert in the react application

Example:

import React, { useCallback } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Alert from '@material-ui/lab/Alert'
import IconButton from '@material-ui/core/IconButton'
import CloseIcon from '@material-ui/icons/Close'
import Dialog from '@material-ui/core/Dialog'


const useStyles = makeStyles(theme => ({
    root: {
        '& > * + *': {
            marginTop: theme.spacing(2),
        },
        width: '100%',
    },
}))

export default function TransitionAlerts(props) {
    const classes = useStyles()
    return (
        <div className={classes.root}>
            <Dialog open={props.open}>
                <Alert
                    action={
                        <IconButton
                            aria-label='close'
                            color='inherit'
                            size='small'
                            onClick={
                              useCallback(() => props.closeAlert({msg: '', open: false }))
                            }
                        >
                            <CloseIcon fontSize='inherit' />
                        </IconButton>
                    }
                >
                    {props.msg}
                </Alert>
            </Dialog>
        </div>
    )
}
Related