I have a form completed with info requested from the database. But the form is not letting me update the form, I can't write anything on the input. What I am using wrong?
After a Graphql query, the title is store in the jsonFromDataBase variable. If the query is empty I want nothing in my input, if it's not, I eant the title but I also want to be able to change it. The problem is that the title is not letting write anything
Here is what my code looks like:
const Form = () => {
useEffect(() => {
KeyUtils.resetGenerator();
}, []);
const [newTitle, setNewTitle] = useState("");
return (
<Title
type="text"
value={jsonFromDataBase.title ? jsonFromDataBase.title : newTitle}
placeholder="Title"
onChange={e => {
setNewTitle(e.target.value);
}}
required
/>
)
}
const Title = styled.input`
margin-bottom: 10px;
padding: 10px;
border: 1px solid white;
`;
export default Form;
The problem is controlled vs uncontrolled inputs.
Since you're setting the value from an initial (I assume?) ajax / web query, it appears your setNewTitle
isn't updating jsonFromDataBase.title
- or if it is, you'll need to fetch the value again in the onChange handler.
If you want to use a controlled input (ie, handled with value
and onChange
) then you should have your initial call to the database fill in the state
- NOT the value directly.
If you want to use uncontrolled inputs, you can set a default value for the input without changing it to a controlled input by using the defaultValue
prop, rather than value
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.