I have this function that sends a post request to my express backend
function postFood (foodName, foodType, foodDescription){
Axios.post("http://localhost:3001/food", {
foodName: foodName,
foodType: foodType,
foodDescription: foodDescription,
}).then(() => {
console.log("food created successfully" + foodName, foodType, foodDescription);
});
};
This is my React component that takes the user input(foodName, foodType, foodDescription) and
stores them in states and should send them to my backend ONLY when pressing the submit button
but it sends the information everytime i make a change to any of the input fields
import React, { useState } from "react";
import postFood from "./Services/createFood";
function NewFood({ closeFoodForm }) {
const [foodName, setfoodName] = useState("");
const [foodType, setfoodType] = useState("Hamburger");
const [foodDescription, setfoodDescription] = useState("");
// this function gets called everytime i make a change to the input fields.
postFood(foodName, foodType, foodDescription);
return (
<div className="CreateNewFood">
<form id="foodForm" >
<label>Name</label>
<input
onChange={e => {
setfoodName(e.target.value);
}}
id="inputFoodName"
name="foodName"
></input>
<select id="inputFoodType" name="foodType"
onChange={e => setfoodType(e.target.value)}>
<option value="hamburger">Hamburger</option>
<option value="pizza">Pizza</option>
<option value="kebab">Kebab</option>
</select>
<label>Description</label>
<textarea
onChange={e => {
setfoodDescription(e.target.value);
}}
id="inputFoodDescription"
placeholder="big hamburger with double patties "
name="foodDescription"
></textarea>
//when i press this button i would like to submit the form
<button type="Submit" value="Submit" id="submitButton" onClick={postFood}>
Create
</button>
</form>
</div>
);
}
2
Answers
You are calling
postFood
on every rerender. Remove this:And edit the
<button />
element like so:Note: you should probably not use
onClick
, instead useonSubmit
on the<form />
element and removeonClick
from the submit button.Try it like this
And remove the line
Otherwise every change on the state is going to trigger the function