Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to store input data as objects in an array?

How do I store the input data as objects in an array using useState? Please help.
I need help. I am not able to get the desired output to display the input values.

const Form = () => {
      const [allNotes, setAllNotes] = useState([{}]);
      const [notes, setNotes] = useState({
        name: "",
        age: "",
        class: "",
        request: "",
      });
    
      const nameChangeHandler = (event) => {
        setNotes((prevState) => {
          const newState = { ...prevState, name: event.target.value };
          return newState;
        });
      };
      const ageChangeHandler = (event) => {
        setNotes((prevState) => {
          const newState = { ...prevState, age: event.target.value };
          return newState;
        });
      };
      const classChangeHandler = (event) => {
        setNotes((prevState) => {
          const newState = { ...prevState, class: event.target.value };
          return newState;
        });
      };
      const requestChangeHandler = (event) => {
        setNotes((prevState) => {
          const newState = { ...prevState, request: event.target.value };
          return newState;
        });
      };
    
      const submitHandler = () => {
        setAllNotes((prevState) => {
          const newState = {
            ...prevState,
            name: notes.name,
            age: notes.age,
            class: notes.class,
            request: notes.request,
          };
          return newState;
        });
      };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Everything looks good, maybe except for two small mistakes:

  • Let’s make the initial state for all notes just an empty array, like

    const [allNotes, setAllNotes] = useState([]);

  • The new array inside the setAllNotes should be array not object, like:

    const submitHandler = () => {
      setAllNotes((prevState) => {
        const newState = [
          ...prevState,
          {
            name: notes.name,
            age: notes.age,
            class: notes.class,
            request: notes.request,
          }
        ];
        return newState;
      });
    };

Hope this makes it work!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading