I have this error and I started to learn React last week so I couldn't solve the problem.
Uncaught TypeError: contacts is not iterable
at onSubmit (index.js:15:1)
Contacts Component
import List from "./List"
import Form from "./Form"
import {useState,useEffect} from "react"
import React from "react"
function Contacts(){
const [contacts,setContacts] = useState([]);
useEffect(()=>{
console.log(contacts)
},[contacts])
return (
<div>
<List/>
<Form addContact = {setContacts} contacts={contacts}/>
</div>
)
}
export default Contacts
Form Component
import React from "react"
import { useState } from "react"
function Form(addContact,contacts){
const [form,setForm] = useState({fullName : "" , phoneNumber : ""})
const onChangeInput = (event) => { setForm({...form,[event.target.name]: event.target.value}) }
const onSubmit = (event) => {
event.preventDefault();
if(form.name ==="" || form.phoneNumber===""){
return false
}
addContact([...contacts , form]);
}
return (
<form onSubmit={onSubmit}>
Form List
<div><input name="fullName" placeholder="fullName" onChange={onChangeInput}></input></div>
<div><input name="phoneNumber" placeholder="phoneNumber" onChange={onChangeInput}></input></div>
<div>
<button>Add</button>
</div>
</form>
)
}
export default Form
CodePudding user response:
please use props like this wrap with {}
function Form({ addContact, contacts }){
...
...
...
}