Why is my Date and Time input not working?

Viewed 34

I have a React frontendand I have styled it using Material UI design.I added the Date and Time component styling to my form and now the form is not able to take up the "name" value and further process with the posting.The prob is only happening in the Date and time input feilds here is the error "TypeError: Cannot read properties of undefined (reading 'name')".... Pls check out my code thanks.

function ReservationForm(){
    const navigate = useNavigate();
    const params = useParams();
    const {user}=useContext(Cont)


    
    const[reservationData,setReservationData]=useState({
        name:"",
        date:"",
        time:"",
        num:"",
        contact:"",
        occasion:"",
    });
    function handleReservationChange(event){
        setReservationData({
            ...reservationData,
            [event.target.name]: event.target.value,
        })
    }
    
    function handleReservationSubmit(event){
        event.preventDefault();
        const newReservation={
            ...reservationData,
            restaurant_id: params.id,
            user_id: user.id,
        };

        fetch(`/reservations`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(newReservation),
          })
            .then((r) => r.json())
            .then(
                setReservationData({
                name:"",
                date:"",
                time:"",
                num:"",
                contact:"",
                occasion:"",
              })
            );
          navigate("/myreservations");
        }

    
    return(
        <>
          <Box
        component="form"
        sx={{
          "& > :not(style)": { m: 1 },
        }}
        noValidate
        autoComplete="off"
        onSubmit={handleReservationSubmit}
      >
       <h1 className="editheadings">Reserve ️</h1> 
      
       <FormControl  className="inputstyle">
          <InputLabel htmlFor="component-outlined">Name</InputLabel>
          <OutlinedInput
            type="text"
            name="name" 
            id="name"
            value={reservationData.name} 
            onChange={handleReservationChange} 
            label="Name"
          />
        </FormControl>
        <br />
        <FormControl>
          <LocalizationProvider   name="date" dateAdapter={AdapterDayjs}  fullWidth>
            <DatePicker
            name="date"
              label="Date"
              value={reservationData.date}
              onChange={handleReservationChange}
              renderInput={(params) => <TextField {...params} />}
              
            />
          </LocalizationProvider>
        </FormControl>
        <FormControl>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <TimePicker
   name="time" label="Time"
              value={reservationData.time} onChange={handleReservationChange}
              renderInput={(params) => <TextField {...params} />}
            />
          </LocalizationProvider>
        </FormControl>
        <br />
        <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">No. of Guests</InputLabel>
          <OutlinedInput
            type="number"
            name="num"
            value={reservationData.num} onChange={handleReservationChange}
          />
        </FormControl>
        <br />
        <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">Contact</InputLabel>
          <OutlinedInput
            type="tel"
            name="contact"
            value={reservationData.contact} onChange={handleReservationChange}
            placeholder="contact"
          />
        </FormControl>
        <br />
        <FormControl className="inputstyle">
          <InputLabel htmlFor="component-outlined">Occasion</InputLabel>
          <OutlinedInput
            type="text"
            name="occasion"
            value={reservationData.occasion} onChange={handleReservationChange}
          />
        </FormControl>
        <Stack paddingLeft={15} direction="row" id="loginbutton">
          <ColorButton variant="contained" type="submit">
            {" "}
            Update Reservation
          </ColorButton>
        </Stack>

       
       </Box>
        </>
    )
}
export default ReservationForm;
2 Answers

Better to check this function.

function handleReservationChange(event){
        setReservationData({
            ...reservationData,
            [event.target.name]: event.target.value,
        })
    }

Based on this function, every field should have name property. But as you can see some of them have not that property.

Since DatePicker and TimePicker onChange events send the new value instead of event, you need to add new handleChange function for DatePicker and TimePicker components like:

function handleReservationChangeWithNameAndValue(name, newValue) {
    setReservationData({
      ...reservationData,
      [name]: newValue
    });
}

and pass it in DatePicker and TimePicker components accordingly:

<DatePicker
  name="date"
  label="Date"
  value={reservationData.date}
  onChange={(newVal) =>
    handleReservationChangeWithNameAndValue("date", newVal)
  }
  renderInput={(params) => <TextField {...params} />}
/>

<TimePicker
  name="time"
  label="Time"
  value={reservationData.time}
  onChange={(newVal) =>
    handleReservationChangeWithNameAndValue("time", newVal)
  }
  renderInput={(params) => <TextField {...params} />}
/>

You can take a look at this sandbox for a live working example of your form with this function.

Related