Reputation: 5150
In the following example the name does not update: https://codesandbox.io/s/react-hooks-usestate-forked-od9th?file=/src/index.js:0-788
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const useForm = initialValues => {
const [values, setValues] = useState(initialValues);
return [
values,
e => {
console.log(e.target.value);
setValues({
...values,
[e.target.name]: e.target.value
});
}
]
}
let count = 0;
const Hello = (props) => {
const [values, handleChange] = useForm({ nameInput: props.name });
count++
console.log(`RenderedAmount: ${values.nameInput} : ${count}`)
return (
<div>
Name: <input value={values.nameInput} onChange={handleChange}/><br/>
Hello {values.nameInput}!
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Hello name="John"/>, rootElement);
Upvotes: 0
Views: 376
Reputation: 1719
You forgot to give the name to the input.
As you are doing [e.target.name]: e.target.value
.
If the name of the input is undefined, you will have {"": value}
in your state
<input value={values.nameInput} onChange={handleChange} name="nameInput" />
Upvotes: 2