simonxcode
simonxcode

Reputation: 143

Storing Multiple Form submission containing multiple inputs with React

I am building a signup form containing multiple inputs(username, date of birth, etc). After a form is submitted it is stored somewhere containing a list of previous submitted forms.

Link to working sample: https://codesandbox.io/s/react-form-multiple-storage-xcmt3i?file=/src/App.js

Codebase for working sample:

import React, { useState } from "react";

const App = () => {
  const [values, setValues] = useState({
    userName: "",
    dateOfBirth: ""
  });

  const [submissions, setSubmission] = useState([
    {
      userName: "april123",
      dateOfBirth: "2000-01-01"
    }
  ]);

  const addSubmission = (values) => {
    const newSubmissions = [...submissions, { values }];
    setSubmission(newSubmissions);
    console.log(submissions);
  };

  const handleChange = (event) => {
    const value = event.target.value;
    setValues({
      ...values,
      [event.target.name]: value
    });
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    addSubmission(values);
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <h1> Signup Form </h1>
        <div>
          <label>username</label>
          <input
            type="text"
            name="userName"
            onChange={handleChange}
            value={values.userName}
            required
          />
        </div>
        <div>
          <label>Date of Birth</label>
          <input
            type="date"
            name="dateOfBirth"
            onChange={handleChange}
            value={values.dateOfBirth || ""}
          />
        </div>
        <div>
          <input type="submit" value="Submit" />
        </div>
      </form>
    </>
  );
};

export default App;

Questions:

  1. Is addSubmission setup properly for what I am trying to achieve? Or can it be improved?
  2. Base on console.log() placement, why am I only seeing previous submissions and not current? Screenshot below for details.

form submission

Upvotes: 0

Views: 1232

Answers (1)

mynameisgeoff123
mynameisgeoff123

Reputation: 96

  1. Your addSubmission isn't consistent, you initialize it as an array of Objects, but when you add a submission to it you are adding an extra value key, as seen in your second log, where the value at index 1 is an object with a key of value. To resolve this, simply remove the bracket
const newSubmissions = [...submissions, values];

You should also clear the current state values after you have successfully submitted an entry.

  1. SetState is async, which means React might still be updating the state when your console.log is called, and that's why you wouldn't see the current submission, if you place the console.log outside of the function and have it triggered on rerender you would see the new submission.

Upvotes: 1

Related Questions