I'm building a MERN app, I want to let user edit the food name in the prompt box by clicking on the Edit
button.
I was following the instructions in this link: [https://stackoverflow.com/questions/54993218/reactjs-using-alert-to-take-input-from-user]
The issue is when I click on the Edit
button and type in the prompt then click OK, it will receive the null value for the first time, but it won't update the database.
And then when I click the Edit
button again, without input anything to it then press OK, it will receive the value from the first time input and update it to database (like a delay).
What I want is: when click on the Edit
button, it will display the prompt box and take the value from the prompt box and update to the database when the user clicks OK.
Is there any way I can fix this? Thank you everyone!
Here's my demo: gif
Here's my code:
function FoodListTable(props) {
/* Definition of handleClick in component */
const [newFoodName, setNewFoodName] = useState("")
const handleEdit = () => {
const enteredFood = prompt('Please enter your new food:')
setNewFoodName(enteredFood)
console.log(newFoodName)
if (newFoodName) {
Axios.put("https://mern-lefood.herokuapp.com/update", {
newFoodName: newFoodName,
id: props.val._id
})
}
}
return (
<button onClick={handleEdit}>Edit</button>
)
}
CodePudding user response:
React this.setState
, and useState
does not make changes directly to the state object.
React this.setState
, and React.useState
create queues for React core to update the state object of a React component.
So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.
Try below code that's works !
function FoodListTable(props) {
/* Definition of handleClick in component */
const [newFoodName, setNewFoodName] = useState("");
const handleEdit = () => {
const enteredFood = prompt('Please enter your new food:');
setNewFoodName(enteredFood);
if (enteredFood) {
Axios.put("https://mern-lefood.herokuapp.com/update", {
newFoodName: enteredFood,
id: props.val._id
})
}
}
return (
<button onClick={handleEdit}>Edit</button>
)
}
For more detail Click here