简体   繁体   中英

React Bootstrap Modal Popup in Axios?

** More info added, I didn't have the full component shown **

I currently have an alert window that pops up on a website when a booking request form is filled out. If the email was sent then it is a success alert and if not then it lets you know the email was not sent. I'm trying to swap these to a React Bootstrap Modal window, but cannot get them to successfully open the modal window, the next page loads with no modal.

Note: I have tried calling handleShow() in my form onSubmit as well as in the onClick() of my form submit button but the modal window does not show either way.

export default function BookingFormPrivate() {
    const { shows, getShows } = useContext(ShowContext)
    const [ name, setName ] = useState('')
    const [ email, setEmail ] = useState('')
    const [ phone, setPhone ] = useState('')
    const [ venue, setVenue ] = useState('')
    const [ location, setLocation ] = useState('')
    const [ time, setTime ] = useState('')
    const [ url, setUrl ] = useState('https://www.')
    const [ emailBody, setEmailbody ] = useState('')
    const [ type, setType ] = useState('Private')
    const [ events, setEvents ] = useState('')
    const [ showDate, setShowDate ] = useState('')

    useEffect(() => {
        getShows()
    }, [])

    const inputs = {
        name,
        email,
        phone,
        emailBody,
        events,
        venue,
        location,
        time,
        showDate,
        url,
        type
    }

    const [showModal, setShowModal] = useState(false);
    const handleShow = () => setShowModal(true);
    const handleClose = () => setShowModal(false);

    const sendMessage = () => {
        console.log(inputs)
        axios
            .post('/sendBooking', inputs)
            .then(res => {
                if (res.data.status === 'success') {
                    return (
                        <Modal.Dialog show={showModal} onHide={handleClose}>
                            <Modal className='modal fade' id='myModal'>
                                <Modal.Header className='modal-header'>
                                    <h5 className='modal-title'>Private Booking Email Sent</h5>
                                    <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </Modal.Header>
                                <Modal.Body className='modal-body'>
                                    <p>A message about your private event has been sent, we will get back to you as soon as possible. </p>
                                </Modal.Body>
                                <Modal.Footer className='modal-footer'>
                                    <button className='btn btn-primary' data-dismiss='modal' onClick={handleClose}>Close</button>
                                </Modal.Footer>
                            </Modal>
                        </Modal.Dialog>
                    )
                } else if (res.data.status === 'fail') {
                    alert("Message failed to send, please try again.")
                }        
            })
            .catch(error => {
                console.error(error)
            })
    }
    const clearInputs = () => {
        setName('')
        setEmail('')
        setPhone('')
        setEmailbody('')
        setEvents('')
        setVenue('')
        setLocation('')
        setTime('')
        setShowDate('')
        setUrl('https://www.')
        setType('Private')

        setNewPotentialShowInfo({
            name: '',
            phone: '',
            email: '',
            emailBody: '',
            venue: '',
            location: '',
            time: '',
            date: '',
            type: 'Private',
            url: 'https://www.'
        })
    }
    const [ newPotentialShowInfo, setNewPotentialShowInfo ] = useState({
            name: '',
            phone: '',
            email: '',
            emailBody: '',
            venue: '',
            location: '',
            time: '',
            date: '',
            type: 'Private',
            url: 'https://www.'
    })
    const { addPotentialShow } = useContext(ShowContext)

    const newPotentialShowFunction = () => {
        addPotentialShow(newPotentialShowInfo)
            .then(() => {
                clearInputs()
            })
            .catch(err => console.error(err.response.data.message))
    }
    const handleSubmit = e => {
        e.preventDefault();
        sendMessage();
        newPotentialShowFunction();
        // handleShow();
    }
    const handleChange = e => {
        console.log(newPotentialShowInfo)
        const { name, value } = e.target
        setNewPotentialShowInfo(prevPotentialShow => ({
            ...prevPotentialShow,
            [name]: value
        }))
            if( name === 'name' ){
                setName(value)
            } else if ( name === 'phone' ){
                setPhone(value)
            } else if ( name === 'email' ){
                setEmail(value)
    }

    const dateChange = (date) => {
        console.log(newPotentialShowInfo)
        const dateString = date.toString()
        const shortDate = dateString.slice(0, 15)
        setEvents(shortDate)
        console.log(shortDate)
        // setDate(date)
        setNewPotentialShowInfo(prevPotentialShow => ({
            ...prevPotentialShow,
            date:shortDate
        }))
    }

    const result = shows && shows.map(dates => (dates.date))
    const checkDateDisable = (data) => {
        return result.includes(new Date(data.date).toISOString())
    }

    return(
        <div className='bookingContainer'>
            <form className='bookingForm' onSubmit={handleSubmit}>
                <h3 className='formIntro'>PLEASE FILL OUT FORM TO<br/>REQUEST A PRIVATE EVENT</h3>
                <input type='text'
                        placeholder='Full Name'
                        name='name'
                        className='formInput'
                        required='required'
                        value={name}
                        onChange={handleChange}
                />
                <input type='email'
                        placeholder='E-mail'
                        name='email'
                        className='formInput'
                        required='required'
                        value={email}
                        onChange={handleChange}
                />
                <button type='submit' className='formButton' onClick={handleShow}>
                    Submit
                </button>
            </form>
            <div className='bookingCalendarPrivate'>
                <Calendar
                    onChange={dateChange}
                    value={events.date}
                    tileDisabled={checkDateDisable}
                    calendarType="US"
                />
            </div>
        </div>
    )
}

Try using the useEffect() hook ( https://reactjs.org/docs/hooks-effect.html ) for performing http requests. useEffect() takes a callback function which is executed after your component has mounted to the DOM. The second argument to useEffect() is an array of dependencies. In this case, we pass an empty array since I'm assuming you need this block of code to execute only once.

Also, your state variables need to be inside the component for them to be accessed correctly.

const SendMessage = props => {
    const [showModal, setShowModal] = useState(false);
    const handleShow = () => setShowModal(true);
    const handleClose = () => setShowModal(false);

    useEffect(() => {
       axios
         .post('/sendBooking', inputs)
         .then(res => {
           if (res.data.status === 'success') {
              handleShow();
           } else if (res.data.status === 'fail') {
              alert("Message failed to send, please try again.");
           }
         })
    }, []);

    return (
      {showModal ? (
        <Modal.Dialog show={handleShow} onHide={handleClose}>
          <Modal className='modal fade' id='myModal'>
            <Modal.Header className='modal-header'>
              <h5 className='modal-title'>Private Booking Email Sent</h5>
              <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </Modal.Header>
            <Modal.Body className='modal-body'>
              <p>A message about your private event has been sent, we will get back to you as soon as possible. </p>
            </Modal.Body>
            <Modal.Footer className='modal-footer'>
              <button className='btn btn-primary' data-dismiss='modal' onClick={handleClose}>Close</button>
            </Modal.Footer>
          </Modal>
         </Modal.Dialog>
       ) : null}
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM