简体   繁体   中英

Add Object to an Array with a Form in React

I am trying to have a form on my react site that someone can fill out and it would add a new item in my list. I am trying to do this using "react-hook-form" which seems easy to setup and work with. It does capture the information when I console.log and check. I am trying to now add that to my array.

App.js (In this file I have the array withe objects along with my component I have passed in the props.

import { useState } from 'react';
import './App.css';
import HeroeList from './HeroeList';
import NavBar from './NavBar';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import AddHero from './AddHero';
import HeroDetail from './HeroDetail';

function App() {
  const [heroes, setHeroes] = useState([
    { heroName: 'Superman', pic: 'https://cosmicbook.news/sites/default/files/henry-cavill-justice-league-brhv.jpg', powers: 'Flight, Speed, Strength', bio: 'Superman was born on the planet Krypton and was given the name Kal-El at birth. As a baby, his parents sent him to Earth in a small spaceship moments before Krypton was destroyed in a natural cataclysm', id: 1 },
    { heroName: 'Flash', pic:'https://hdqwalls.com/wallpapers/flash-justice-league-unite-2017-on.jpg', powers: 'Super Speed, Time Travel', bio: 'Barry Allen is The Flash, the fastest man alive. Using his super-speed powers, he taps into the Speed Force and becomes a costumed crime-fighter', id: 2},
    { heroName: 'Wonder-Women', pic:'https://images.hdqwalls.com/download/justice-league-wonder-woman-2018-yy-1080x2160.jpg', powers: 'Strength, Speed, Lasso of truth', bio: 'Wonder Woman is the princess Diana, the daughter of Hippolyta, Queen of the Amazons and Zeus, the mightiest of the Gods of Olympus.', id: 3},
    { heroName: 'Batman',pic:'https://images.hdqwalls.com/download/batman-justice-league-unite-2017-qu-720x1280.jpg', powers: 'Super intelligence', bio:'Batman is the superhero protector of Gotham City, a tortured, brooding vigilante dressed as a sort of human bat who fights against evil and strikes fear into the hearts of criminals everywhere.', id: 4}
  ])
  return (
    <Router>
      <div className="App">
        <NavBar />
        <Switch>
          <Route exact path="/">
            <HeroeList heroes={heroes}/>
          </Route>
          <Route path="/AddHero">
            <AddHero heroes={heroes} setHeroes={setHeroes}/>
          </Route>
          <Route path="/HeroDetail/:id">
            <HeroDetail heroes={heroes}/>
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;

AddHero.js (In this file I have my form setup with userForm())

import { useState } from "react";
import { useForm } from "react-hook-form";

const AddHero = (setHeroes, heroes) => {
    
    const {register, handleSubmit, errors} = useForm()

    const onSubmit = (data) => {
        setHeroes(heroes => [...heroes, data])
        console.log(data)
        
    }

    
    
    return ( 
        <form onSubmit={handleSubmit(onSubmit)}>
                <label>Hero Name:</label>
                <input type="text" name="HeroName" placeholder="Hero-Name" ref={register}/>
                <label>Hero Powers:</label>
                <input type="text" name="HeroPower" placeholder="Hero-Power" ref={register}/>
                <label>Hero Bio:</label>
                <textarea type="text"/>
                <input type="submit"/>
        </form>
     );
}
 
export default AddHero;

I am trying to use useState to set the the new object in the array. I am getting an error.

Uncaught (in promise) TypeError: setHeroes is not a function

In Line 4 of AddHero.js, you are doing:

const AddHero = (setHeroes, heroes) => {

However, setHeros and heroes are not being passed into the component. Instead, the props object is. To fix this, simply wrap setHeroes, heroes in curly braces:

const AddHero = ({ setHeroes, heroes }) => {

Edit: I also noticed that your onSubmit is using the return value of a function instead of binding to that function.

<form onSubmit={handleSubmit(onSubmit)}>

This should be a function:

<form onSubmit={() => handleSubmit(onSubmit)}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM