简体   繁体   中英

ReactJS: How To Get Input Value From The Prompt Box And Update It To Database

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>
    )
}

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM