I’m trying to get both the name and email value in App.js through handler, but I cannot get the name and only get the email value through object state.
AddContacts.js :-
let [main, setMain] = useState({
name: "",
email: ""
});
function func1(evt) {
setMain({ name: evt.target.value });
}
function func2(evt) {
setMain({ email: evt.target.value });
}
return (
<>
<div className="mb-3">
<label className="form-label">Name</label>
<input type="text" className="form-control" id="exampleFormControlInput1" placeholder="Your name" value={main.name} onChange={func1} />
</div>
<div className="mb-3">
<label htmlFor="exampleFormControlInput1" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleFormControlInput1" placeholder="[email protected]" onChange={func2} />
</div>
<button className='btn btn-primary' onClick={() => { props.handler(main) }}>Add</button>
</>
)
App.js :-
import AddContacts from './components/AddContacts';
import './App.css';
import {useState} from 'react';
function App() {
let [obj, setObj] = useState([]);
const func = (main) => {
console.log(main.name);
console.log(main.email);
}
return (
<div className="container">
<AddContacts handler={func}/>
</div>
);
}
export default App;
Expecting to print the name and the email in console, but I get only the email and the name is shoing undefined.
2
Answers
Because you are overwriting the values here:
You’ll want to pass both values:
though there are better ways to avoid code duplication, like just having single update function such as:
and call that same function when updating either name or email
onChange={func}
You should use the callback function approach for updating state values if you have an object as a value