I am new to React and I am currently building a recipe website to add/edit/delete recipes inside a database (Django). My issue is I have my backend set up and the proper JSON format, but I do not know how to properly manipulate the data on my front end to eventually send to my back end. Code and problem is as follows.
JSON
{
"id": 1,
"name": "Pizza",
"description": "Good Pizza",
"ingredients": [
{
"ingredients": "cheese"
}
]
}
React
const Home = () => {
const [item, setItem] = useState({
name: "",
description: "",
ingredients: [{
ingredients: ''
}],
});
const handleInputChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
if (name === "ingredients") {
setItem({ ingredients: [{ [name]: value }] });
} else {
setItem({ [name]: value });
}
};
console.log(item); // using to keep track of what has changed
return (
<div>
<form>
<input
name="name"
type="text"
value={item.name}
onChange={handleInputChange}
/>
<input
name="ingredients"
type="text"
value={item.ingredients[0].ingredients} // im like 200% sure this is wrong...
onChange={handleInputChange}
/>
</form>
</div>
);
};
export default Home;
Submitting user input to name, or description is working fine, but I am running into all sorts of issues as soon as I try to add ingredients, and I cannot seem to find the right way forward. I understand my code is minimal on the react side, but I wanted to get the ingredients down before I proceeded to adding anything else (adding extra inputs, styling, REST operations). Thank you!
setItem, you should probably use the spread operator..., in your current code, you are setting the item to a new object entirely. For example, insetItem({[name]:value}), you are setting the state to become an object with one key only. To keep the object with the same keys and only modify the one you want, instead usesetItem({...item, [name]:value})