skip to Main Content

I am working with react and I want to implement a post request with axios. I have tried several ways, but I don’t know why after clicking on submit button no object is returned. Here is my code:

export default function NewRequestForm(props) {
    const [country, setCountry] = useState('');
    const [city, setCity] = useState('');
    const [arrival_date, setArrivalDate] = useState('')
    const [departure_date, setDepartureDate] = useState('');
    const [arrival_date_is_flexible, setIsArrDateFelxible] = useState(false);
    const [departure_date_is_flexible, setIsDptDateFelxible] = useState(false);
    const [message, setMessage] = useState('');

    const handleChangeCountry = (event) => {
        setCountry(event.target.value);
    }

    const handleChangeCity = (event) => {
        setCity(event.target.value);
    }

    const handleChangeArrivalDate = (event) => {
        setArrivalDate(event.target.value);
    }

    const handleChangeDepartureDate = (event) => {
        setDepartureDate(event.target.value);
    }

    const handleChangeMessage = (event) => {
        setMessage(event.target.value);
    }

    const handleChangeIsArrDateFlexible = (event) => {
        setIsArrDateFelxible(event.target.value);
    };
    const handleChangeIsDptDateFlexible = (event) => {
        setIsDptDateFelxible(event.target.value);
    };
    
    const [values, setValues] = useState(intialState);
    
    const handleChange = (prop) => (event) => {
        setValues({
            ...values,
            [prop]: event.target.value,
        });
    };

    // Data Validation and Send to Backend
    const onSubmit = async (e) => {
        e.preventDafault();
        axios.post("http://127.0.0.1:8000/announcement/create", {
            country : country,
            city : city,
            arrival_date: arrival_date,
            departure_date: departure_date,
            arrival_date_is_flexible: arrival_date_is_flexible,
            departure_date_is_flexible: departure_date_is_flexible,
            message: message,
            })
            .then((res) =>{
                console.log(res.data)
            });
        }


    const handleClose = () => {
        props.setOpen(false);
    };

    const onCancle = () => {
        props.setRequestData({});
        setValues(intialState);
    };

    return (
        <Dialog 
            open={props.open}
            onClose={handleClose}
            aria-labelledby="responsive-dialog-title"
            >
                <Box className="add-request-center-element" sx={{ m: 2, maxWidth: "100%" }}>
                    <Box className="request-management-add-request">
                        <Grid container spacing={3}>
                            <Grid item xl={12} lg={12} md={12} sm={12} xs={12}>
                                <Box className="add-request-center-element">
                                    <form className="add-request-form">
                                        <Box>
                                            <Box className="add-request-center-element form-title">
                                                <h1 style={{ marginBottom: "3rem"}}>Enter The Trip Info</h1>
                                            </Box>
                                            <Grid container spacing={2}>
                                                {/* country name */}
                                                <Grid item xl={6} lg={6} md={6} sm={12} xs={12}>
                                                    <FormControl sx={{width: "100%"}}>
                                                        <TextField 
                                                            id="new-request-country"
                                                            name="country"
                                                            type="text"
                                                            label="Country"
                                                            variant="outlined"
                                                            inputProps={{maxLength: 20}}
                                                            onChange={handleChangeCountry}
                                                            required/>
                                                    </FormControl>
                                                </Grid>
                                                {/* city name */}
                                                <Grid item xl={6} lg={6} md={6} sm={12} xs={12}>
                                                    <FormControl sx={{width: "100%"}}>
                                                        <TextField 
                                                            id="new-request-city"
                                                            name="city"
                                                            type="text"
                                                            label="City"
                                                            variant="outlined"
                                                            inputProps={{maxLength: 20}}
                                                            onChange={handleChangeCity}
                                                            required/>
                                                    </FormControl>
                                                </Grid>
                                                {/* Arrival Date */}
                                                <Grid item xl={6} lg={6} md={6} sm={12} xs={12}>
                                                    <FormControl sx={{ mt: 1 }}
                                                                style={{ width: "100%" }}
                                                                className="rtlDatePicker">
                                                        <DatePicker 
                                                            animations={[
                                                                transition({
                                                                    from: 35,
                                                                    transition: "all 400ms cubic-bezier(0.335, 0.010, 0.030, 1.360)",
                                                                })
                                                            ]}
                                                            style={{ width: "100%"}}
                                                            inputClass="new-request-date-picker-input"
                                                            className="date-picker"
                                                            format="YYYY/MM/DD"
                                                            name="arrival_date"
                                                            calendarPosition="bottom-end"
                                                            placeholder="Arrival Date *"
                                                            hideOnScroll
                                                            editable
                                                            // onChange={handleChangeArrivalDate}
                                                            />
                                                    {/*  arrival date is flexible */}
                                                    <FormControlLabel
                                                        control={<Checkbox 
                                                                    value="arrivaldateisflexible" 
                                                                    color="primary" 
                                                                    onChange={handleChangeIsArrDateFlexible}
                                                                    />}
                                                        label="Arrival date is flexible"
                                                    />
                                                    </FormControl>
                                                </Grid>
                                                {/* Departure Date */}
                                                <Grid item xl={6} lg={6} md={6} sm={12} xs={12}>
                                                    <FormControl sx={{ mt: 1 }}
                                                                style={{ width: "100%" }}
                                                                    className="rtlDatePicker">
                                                        <DatePicker 
                                                            animations={[
                                                                transition({
                                                                    from: 35,
                                                                    transition: "all 400ms cubic-bezier(0.335, 0.010, 0.030, 1.360)",
                                                                })
                                                            ]}
                                                            style={{ width: "100%"}}
                                                            inputClass="new-request-date-picker-input"
                                                            className="date-picker"
                                                            format="YYYY/MM/DD"
                                                            name="departure_date"
                                                            calendarPosition="bottom-end"
                                                            placeholder="Departure Date *"
                                                            hideOnScroll
                                                            editable
                                                            required
                                                            minDate={values.arrival_date}
                                                            // onChange={handleChangeDepartureDate}
                                                            />
                                                    </FormControl>
                                                    {/* departure date is  flexible */}
                                                    <FormControlLabel
                                                        control={<Checkbox 
                                                                    value="arrivaldateisflexible" 
                                                                    color="primary"
                                                                    onChange={handleChangeIsDptDateFlexible}
                                                                    />}
                                                        label="Departure date is flexible"
                                                    />
                                                </Grid>
                                                {/* Travelers count */}
                                                {/* message */}
                                                <Grid item xl={12} lg={12} md={12} sm={12} xs={12}>
                                                    <FormControl sx={{width: "100%"}}>
                                                        <TextField 
                                                            id="new-request-message"
                                                            name="message"
                                                            type="text"
                                                            label="Message"
                                                            variant="outlined"
                                                            multiline 
                                                            fullWidth="true"
                                                            size="medium"
                                                            rows={10}
                                                            maxRows={10}
                                                            onChange={handleChangeMessage}
                                                            />
                                                    </FormControl>
                                                </Grid>
                                                {/* Confirm Button */}
                                                <Grid item xl={6} lg={6} md={6} sm={12} xs={12}>
                                                    <Button
                                                        variant="contained"
                                                        sx={{ width: "100%" }}
                                                        type="submit"
                                                        onClick={onSubmit}
                                                    >
                                                        Submit the information
                                                    </Button>
                                                </Grid>
                                                {/* Quit */}
                                                <Grid sx={{ display: "flex", justifyContent: "flex-end" }} item xl={6} lg={6} md={6} sm={12} xs={12}>
                                                    <Button
                                                        variant="outlined"
                                                        sx={{
                                                        width: "1000%",
                                                        }}
                                                        type="submit"
                                                        onClick={onCancle}
                                                    >
                                                        Quit
                                                    </Button>
                                                </Grid>
                                            </Grid>
                                        </Box>
                                    </form>
                                </Box>
                            </Grid>
                        </Grid>
                    </Box>
                </Box>
        </Dialog>
        
    );

}

And this is the code where I call NewRequestForm component:

 export default function HeaderComponent(props) {
        const [disabled, setDisabled] = useState(false);
        const [open, setOpen] = useState(false);
        const [requestData, setRequestData] = useState({});
    
    const openCreateRequest = (event) => {
        setOpen(true);
        setDisabled(false);
    }
    const header = (
        <div className="table-header">
            <div>
            <Button
                varient="contained"
                size="large"
                style={{ minWidth: 150 }}
                onClick={(e) => openCreateRequest()}>
                    Add New Request
            </Button>
            </div>
        </div>
    )
    return (
        <div className="datatable-crud-demo">
            <div className="card">
                <Grid sx={{ marginTop: 2 }} container spacing={2}>
                    <Grid item xs={12}>
                        <DataTable
                            header={header}>
                        </DataTable>
                    </Grid>
                </Grid>
            </div>
            <NewRequestForm 
                open={open}
                setOpen={setOpen}
                disabled={disabled}
                setDisabled={setDisabled}
                setRequestData={setRequestData}
                requestData={requestData}
            />
        </div>
    );
}

Before submitting the info:
enter image description here

After submitting the info:
enter image description here

And also I don’t know why the value of my checkboxes are not saved, because based on this post, there must not be a problem with reading their values.
I was searching the net for two days, and tried many solutions. But no one of them does not solve my problem. I will be really grateful for any help or advice.

2

Answers


  1. In the onSubmit function you call e.preventDafault instead of e.preventDefault. Because of this it is reloading the page and not calling your POST and calling the GET that it calls on page load.

    Login or Signup to reply.
  2. It’s because when you click the submit button the form will send a get request.

    <form className="add-request-form" onSubmit={onSubmit}>

    If a button type is button it will trigger the form onSubmit, remove the onClick={onSubmi} from the button and you good to go.

    You can see the error, e.preventDefault() is not a function.

    Use typescript and you will always avoid these little mistakes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search