Home > Back-end >  Add an object to an array upon submitting form in react
Add an object to an array upon submitting form in react

Time:12-06

I am new to react and I am just playing around with some code to familiarize myself with it.

I have data stored into an array of objects, as if I was bringing it in from a JSON-based API. I am using states so I can remove or add any item to the data.

I have succeeded to remove an element from the array of objects. To add to the list, I am using a form. I have my form setup in Form.js.

Form.js

import { useState } from "react";

function Form() {
    const [name, setName] = useState("");
    const [job, setJob] = useState("");

    const submitForm = (e, {handleSubmit}) => {
        e.preventDefault();
        const newChar = {
            name: e.target.name.value,
            job: e.target.job.value
        }
        handleSubmit(newChar);
        setName('');
        setJob('');
    }

    return (
    <form onSubmit={submitForm}>
      <label htmlFor="name">Name</label>
      <input
        type="text"
        name="name"
        id="name"
        value={name}
        onChange={(e) => setName(e.target.value)} />
      <label htmlFor="job">Job</label>
      <input
        type="text"
        name="job"
        id="job"
        value={job}
        onChange={(e) => setJob(e.target.value)} />
      <input type="submit"/>  
    </form>
  );
}

export default Form;

In App.js, I have initialized my array of objects and I have my function handleSubmit() that will update the state by taking the existing state and adding the new character parameter, using the ES6 spread operator.

import { useState } from "react";
import Form from "./Form";

function App() {
    const [characters, setCharacters] = useState([
      {
        name: 'Charlie',
        job: 'Janitor',
      },
      {
        name: 'Mac',
        job: 'Bouncer',
      },
      {
        name: 'Dee',
        job: 'Aspring actress',
      },
      {
        name: 'Dennis',
        job: 'Bartender',
      },
    ]);
  
    const removeChar = (id) => {
      const newChars = characters.filter(character => characters.indexOf(character) !== id);
      setCharacters(newChars);
    }

    const handleSubmit = (character) => {
      setCharacters([ ...characters, character ]);
      
    }

  return (
    <div className="container">
      <Table characters = {characters} removeChar = {removeChar} />
      <Form handleSubmit = {handleSubmit} />
    </div>
  );
}

export default App;

This code does not work. I cannot seem to figure out why. any help would be greatly appreciated

CodePudding user response:

just try this

 const handleSubmit = (character) => {
      let oldArray  = [...characters]
      oldArray.push(character)
      setCharacters(oldArray);          
    }

Check this Example

 characters = [
          {
            name: 'Charlie',
            job: 'Janitor',
          },
          {
            name: 'Mac',
            job: 'Bouncer',
          },
          {
            name: 'Dee',
            job: 'Aspring actress',
          },
          {
            name: 'Dennis',
            job: 'Bartender',
          },
        ]
      
    const handleSubmit = (character) => {
         let oldArray  = [...characters]
        oldArray.push(character)
        console.log(oldArray)
          //setCharacters([ ...characters, character ]);
        }

    handleSubmit({name:'Waleed',Job:"HOD"})

CodePudding user response:

So I found where the problem was lying. I was passing the {handleSubmit} in the const SubmitForm declaration instead of passing it to the const Form() . Here is the code if it can help anyone new to react.

Form.js

import { useState } from "react";

function Form({handleSubmit}) {
    const [name, setName] = useState("");
    const [job, setJob] = useState("");
  
    const submitForm = (e) => {
        
        e.preventDefault();
        const newChar = {
             name: e.target.name.value,
             job: e.target.job.value
        }
        handleSubmit(newChar);
        setName('');
        setJob('');
    }

    return (
    <form onSubmit={submitForm}>
      <label htmlFor="name">Name</label>
      <input
        type="text"
        name="name"
        id="name"
        value={name}
        onChange={(e) => setName(e.target.value)} />
      <label htmlFor="job">Job</label>
      <input
        type="text"
        name="job"
        id="job"
        value={job}
        onChange={(e) => setJob(e.target.value)} />
      <input type="submit"/>  
    </form>
  );
}

export default Form;

App.js

import { useState } from "react";
import Form from "./Form";

function App() {
    const [characters, setCharacters] = useState([
      {
        name: 'Charlie',
        job: 'Janitor',
      },
      {
        name: 'Mac',
        job: 'Bouncer',
      },
      {
        name: 'Dee',
        job: 'Aspring actress',
      },
      {
        name: 'Dennis',
        job: 'Bartender',
      },
    ]);
  
    const handleSubmit = (character) => {
      setCharacters(characters => [...characters, character])
    }
    
  return (
    <div className="container">
      <Form handleSubmit = {handleSubmit} />
    </div>
  );
}

export default App;

  • Related