简体   繁体   English

通过 PUT 方法更新 object

[英]Updating the object via PUT method

I am creating a to-do application with the MERN stack.我正在使用 MERN 堆栈创建待办事项应用程序。 The backend is the MongoDB database.后端是 MongoDB 数据库。 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.单击该按钮后,架构 viewDetails 中就有此属性,该属性最初保持为 false,但一旦我单击它,它应该使用 true 值更新数据库并类似地切换。我可以在客户端更改 object 值,但在后端,它仍然需要更新。 I want to initiate a PUT call with that specific to-do object and update it in DB.我想用那个特定的待办事项 object 发起一个 PUT 调用并在数据库中更新它。 The code for the same function is given below: Here listitems have all todos objects in it.下面给出了相同 function 的代码: 这里的列表项中包含所有待办事项对象。

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.您可以使用PUT方法更新数据库中的 object。 You can use the axios library to make the PUT request.您可以使用axios库来发出PUT请求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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