I would like to make edit page in my react app but I am struggling how to display value in input form and make it editable. I am getting Recipe data via API and would like to display it to the user, make it editable and send it again with POST request.
If I write:
<input
type="text"
required
value={recipe.title}
onChange={(e) => setTitle(e.target.value)}>
</input>
the title is displayed but cannot be changed in any way
if I write
<textarea
type="text"
required value={title}
onChange={(e) => setTitle(e.target.value)}>
{recipe.title}
</textarea>
nothing is displayed
I suppose the ideal solution is to fetch the data and use it as initial state for useState like this:
const { data: recipe2 } = useFetch(url_recipes `${id}`)
const [title, setTitle] = useState(recipe.title);
<input
type="text"
required
value={title}
onChange={(e) => setTitle(e.target.value)}
></input>
but I am not sure how to do it exactly. Thanks for any help.
CodePudding user response:
As you pointed in your last solution the ideal way is to create a double-way binding with the input and the state (by creating a controlled component). And you do that by giving as value the name of the state and as an onChange handler the correct setState method to update the value of the state. The input will be this one:
<input
type="text"
required
value={title}
onChange={(e) => setTitle(e.target.value)}
></input>
However to make sure the input gets the fetched data as value what you can do is using a useEffect hook to make sure the state gets the data once it has been fetched from the API:
const { data: recipe2 } = useFetch(url_recipes `${id}`)
const [title, setTitle] = useState("");
useEffect(() => {
if(recipe2 && recipe2.title){
setTitle(recipe2.title);
}
}, [recipe2])