skip to Main Content

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


  1. Because you are overwriting the values here:

    function func1(evt) {
        setMain({ name: evt.target.value });
    }
    function func2(evt) {
        setMain({ email: evt.target.value });
    }
    

    You’ll want to pass both values:

    function func1(evt) {
        setMain({ name: evt.target.value, email: evt.target.value });
    }
    function func2(evt) {
        setMain({ name: evt.target.value, email: evt.target.value });
    }
    

    though there are better ways to avoid code duplication, like just having single update function such as:

    function func(evt) {
        setMain({ name: evt.target.value, email: evt.target.value });
    }
    

    and call that same function when updating either name or email onChange={func}

    Login or Signup to reply.
  2. You should use the callback function approach for updating state values if you have an object as a value

    setMain(prevState => {
        return {
           ...prevState,
           email: newValue
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search