Ara
Ara

Reputation: 21

React input field isn't updatable

I have a React/Next app where I can post notes/jobs. I have an edit or update button where on click I get the state of the original post with the populated input fields, but can edit or type anything new into the input fields. Is there something wrong with my onChange={handleChange} that Im not getting.

Thanks

const EditJob = ({ job }) => {
  const [form, setForm] = useState({
    title: job.title,
    company: job.company,
    location: job.location,
    salary: job.salary,
    status: job.status,
    contact: job.contact,
    note: job.note,
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setErrors] = useState({});
  const router = useRouter();

  const handleSubmit = (e) => {
    e.preventDefault();
    let errs = validate();
    setErrors(errs);
    setIsSubmitting(true);
  };

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

  useEffect(() => {
    if (isSubmitting) {
      if (Object.keys(error).length === 0) {
        updateJob();
      } else {
        setIsSubmitting(false);
      }
    }
  }, [error]);

  const updateJob = async () => {
    try {
      const res = await fetch(
        `http://localhost:3000/api/jobs/${router.query.id}`,
        {
          method: "PUT",
          headers: {
            Accept: "application:json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(form),
        }
      );
      router.push("/");
    } catch (error) {
      console.log(error);
    }
  };

  const validate = () => {
    let err = {};

    if (!form.title) {
      err.title = "Title is required";
    }
    if (!form.company) {
      err.company = "Company is required";
    }
    if (!form.location) {
      err.description = "Location is required";
    }

    return err;
  };

  return (
    <Container>
      <h1>Update Job</h1>
      <div>
        {isSubmitting ? (
          <Spinner animation="border" />
        ) : (
          <Row>
            <Col>
              <Form onSubmit={handleSubmit}>
                <Form.Group className="mb-3">
                  <Form.Label>Job Title</Form.Label>
                  <Form.Control
                    error={
                      error.title
                        ? {
                            content: "Please enter a job title",
                            pointing: "below",
                          }
                        : null
                    }
                    label="Title"
                    placeholder="Job Ttile"
                    name="title"
                    value={job.title}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Company</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter company name"
                    name="company"
                    value={job.company}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Location</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter location"
                    name="location"
                    value={job.location}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Salary</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter Salary"
                    name="salary"
                    value={job.salary}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Status</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Just applied"
                    name="status"
                    value={job.status}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Contact</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Is there a contact?"
                    name="contact"
                    value={job.contact}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Note</Form.Label>
                  <Form.Control
                    as="textarea"
                    placeholder="Add notes here"
                    style={{ height: "100px" }}
                    name="note"
                    value={job.note}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Button type="submit">Update</Button>
              </Form>
            </Col>
          </Row>
        )}
      </div>
    </Container>
  );
};

EditJob.getInitialProps = async ({ query: { id } }) => {
  const res = await fetch(`http://localhost:3000/api/jobs/${id}`);
  const { data } = await res.json();

  return { job: data };
};

export default EditJob;

Upvotes: 0

Views: 86

Answers (2)

zeeshan zahoor
zeeshan zahoor

Reputation: 77

Try to use the value like this. use form.salary instead of job.salary

<Form.Control
                type="text"
                placeholder="Enter Salary"
                name="salary"
                value={form.salary}
                onChange={handleChange}
              />

Upvotes: 0

windowsill
windowsill

Reputation: 3649

Since these are controlled inputs the value is always going to be what you put as value.

job doesn't look like it ever changes, I think you want to use form instead, since it's being updated.

Upvotes: 1

Related Questions