0

I've got this state and change function

const [mitarbeiter, setMitarbeiter] = useState({
    lastName: "",
    firstName: "",
    quartal: "",
    snummer: "",
    email: "",
    eintrittsdatum: "",
    austrittsdatum: "",
    isAushilfe: false,
});

const handleChange = (event) => {
    const value = event.target.value;
    
    setMitarbeiter({
        ...mitarbeiter,
        [event.target.name]: value
    });
    console.log(event.target.name)
    console.log(mitarbeiter)
};

This is my input field where i try to insert something and want it to update the lastName value of my state

<input id="name" type="text" placeholder="Name.." defaultValue="" value={mitarbeiter.lastName} onChange={handleChange}/>

Does someone know where my error is? It just creates a new value and does not change the previous one and i cant input any text into the input field

salteax1
  • 67
  • 1
  • 7
  • You have to wait until the next render to see the state change. Also, your input doesn't have a `name`, so using `event.target.name` won't work – CertainPerformance Jun 16 '22 at 03:42
  • You should also use the callback for previous state to spread over it. For example: `setMitarbeiter( prev => { ...prev, [event.target.name]: value }` – Joel Hager Jun 16 '22 at 03:43
  • I thought event.target.name is something i can use when i want to change multiple values. Like when inserting in the lastName field it recognizes that the lastName value should be updatet? – salteax1 Jun 16 '22 at 03:47
  • @CertainPerformance if i have to wait for the next render that seems pretty useless, is there a way to instanly do this or should i just use a normal javascript object and do it that way? – salteax1 Jun 16 '22 at 03:52

0 Answers0