The only other answer I found regarding this was one where the event was not being passed to the function. That is not the case here. I'm clearly passing the event as variable e. I have the button type as submit, so the form is being submitted with the event. Also, the handleChange function works properly with the event. I copied this format over from a Udemy course I was taking and I practically have the exact same thing. The only big difference I can think of is that the Udemy course had all of this logic in a separate component that was imported in and then rendered to the page, where as the form and form handling logic is the main component on this page.
Please look at my code and tell me what I am doing wrong!
Code:
import React, { useState, useEffect } from 'react'
import Router, { withRouter } from 'next/router';
import Layout from '../../components/Layout';
import { Col, Row, Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { createPatient } from '../../actions/patient';
const CreatePatient = ({ router }) => {
const [ values, setValues ] = useState({
error: '',
formData: '',
data: ''
});
const { error, formData } = values;
useEffect(() => {
setValues({
...values,
formData: new FormData()
})
}, [router])
const createPatient = (e) => {
e.preventDefault();
createPatient(formData).then(data => {
if (data.error) {
setValues({ ...values, error: data.error });
}
})
}
const handleChange = name => e => {
const value = e.target.value;
formData.set(name, value);
setValues({ ...values, [name]: value, formData, error: '' });
}
return (
<Layout>
<section className="container pt-3">
<form className="form" onSubmit={ createPatient }>
<div className="row">
<div className="col-md-4 my-2">
<label htmlFor="firstName">First Name</label>
<input type="text" className="form-control" name="firstName" id="firstName" onChange={handleChange('firstName')}/>
</div>
<div className="col-md-4 my-2">
<label htmlFor="lastName">Last Name</label>
<input type="text" className="form-control" name="lastName" id="lastName" onChange={handleChange('lastName')}/>
</div>
</div>
<div className="row">
<div className="col-sm-2">
<button type="submit" className="btn btn-primary">Create</button>
</div>
</div>
</form>
</section>
</Layout>
)
}
export default withRouter(CreatePatient);
