简体   繁体   中英

Updating the object via PUT method

I am creating a to-do application with the MERN stack. The backend is the MongoDB database. Now for every todo, there is a view detail button that allows viewing more information about that specific todo. Once I click that button there is this attribute in schema viewDetails which is initially kept false but once I click it should update the DB with true value and toggle similarly.I can change the object value on the client side but on the backend, it still needs to be updated. I want to initiate a PUT call with that specific to-do object and update it in DB. The code for the same function is given below: Here listitems have all todos objects in it.

const [listItems, setListItems] = useState([]);
<button onClick={()=>handleClick(item._id)}>View Details</button>

const handleClick=(id)=>{
    const newTasks = [...listItems];
    newTasks.map((task)=>{
      if(task._id===id){
        task.viewDetails=!task.viewDetails;
      }
    });
    setListItems(newTasks);
       }
    

You can use the PUT method to update the object in the database. You can use the axios library to make the PUT request.

const handleClick = (id) => {
    const newTasks = [...listItems];
    newTasks.map((task) => {
        if (task._id === id) {
            task.viewDetails = !task.viewDetails;
        }
    });
    setListItems(newTasks);
    axios.put(`http://localhost:5000/api/todos/${id}`, newTasks)
        .then(res => {
            console.log(res);
            console.log(res.data);
        })
        .catch(err => {
            console.log(err);
        })
}

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