Search code examples
javascriptreactjsfunctionuse-state

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

  • 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!