简体   繁体   English

使用 Axios PUT 请求从具有多个对象的数组更新数据

[英]Update data from array with multiple objects using Axios PUT request

I need to update data in an array that has multiple objects where a user will input a new balance that will update the old balance state.我需要更新具有多个对象的数组中的数据,其中用户将输入一个新的余额来更新旧的余额状态。 The array consists of a company name with an array called details, and that array holds objects containing employee information(name, balance, notes), for this question I am just using notes to simplify things.该数组由一个公司名称和一个名为 details 的数组组成,该数组包含包含员工信息(姓名、余额、笔记)的对象,对于这个问题,我只是使用笔记来简化事情。 I am using Axios PUT to access the id of the nested object, I get the id from a Link that is passed via useParams hook.我正在使用 Axios PUT 来访问嵌套对象的 id,我从通过 useParams 钩子传递的链接中获取 id。

My issue is in the Axios PUT request.我的问题出在 Axios PUT 请求中。 Before I had a schema that was just a data object (no arrays were in it) and the PUT req was working fine.在我拥有一个只是数据对象的模式(其中没有数组)并且 PUT req 工作正常之前。 Then I needed to change the schema to an array with multiple objects and now I cannot seem to update the data.然后我需要将架构更改为具有多个对象的数组,现在我似乎无法更新数据。 I am able to target the data through the console log but when I take that code from the console and apply it, the state still doesn't change.我能够通过控制台日志定位数据,但是当我从控制台获取该代码并应用它时,状态仍然没有改变。 Even in Postman, the only way for me to successfully update is to get the Shema from a GET request and paste that schema in the PUT request and change some data in it, then I hit send and it updates, but to get it to update again I need to hit send twice (this shouldn't be, no? ).即使在邮递员中,我成功更新的唯一方法是从 GET 请求中获取 Shema 并将该架构粘贴到 PUT 请求中并更改其中的一些数据,然后我点击发送并更新,但要让它更新再次我需要点击发送两次(这不应该,不是吗?)。

I am able to access the data and render it in other components by mapping it twice as shown below: setBalance(res.data.data.details.map((r) => r.balance));我能够访问数据并通过映射两次将其呈现在其他组件中,如下所示: setBalance(res.data.data.details.map((r) => r.balance));

My question: How can I edit the below code to update the state correctly?我的问题:如何编辑以下代码以正确更新状态? setNotes([...details, res.data.data.details.map((r) => r.notes )]);

However, I am really struggling with how to do this in the Axios PUT request.但是,我真的很困惑如何在 Axios PUT 请求中执行此操作。

Here is my code:这是我的代码:

import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { useParams } from "react-router-dom";
import axios from "axios";

const AddForm = () => {
  const [newBalance, setNewBalance] = useState("");
  const [details, setDetails] = useState([]);
  const [notes, setNotes] = useState("");
  const [total, setTotal] = useState("");
  const { id } = useParams();
  const history = useHistory();

  //update balance
  const updateBal = () => {
  // function to calculate balance
  };

  const updateBalHandler = (e) => {
    e.preventDefault();
    axios({
      method: "PUT",
      url: `http://localhost:5000/update-snapshot-test/${id}`,
      data: { 
              balance: total
              notes: notes 
            },
    }).then((res) => {
      history.push(`/success/` + id);
      setNotes([...details, res.data.data.details.map((r) => r.notes )]); //this code isolates the notes state but does not update it
    });
  };

  return (
    <form
      action="/update-snapshot/:id"
      method="post"
      onSubmit={updateBalHandler}
    >
        <Input
          setInputValue={setNewBalance}
          inputValue={newBalance}
          inputType={"number"}
        />

        <Input
          setInputValue={setTotal}
          inputValue={total}
          inputType={"number"}
        />

        <TextArea
         setInputValue={setNotes}
         inputValue={notes}
         inputType={"text"}
        />

        <Button onClick={() => { updateBal(); }} >
        Update
       </Button>

        <Button type="submit">
         Save
        </Button>

    </form>
  );
};
export default AddForm;

Here is my data structure from Mongo DB这是我来自 Mongo DB 的数据结构

{
    "message": "Post found",
    "data": {
        "company": "Riteaid",
        "_id": "1",
        "details": [
            {
                "employee": "jane doe",
                "balance": "3",
                "notes": "some notes",
                "_id": "2"
            },
            {
                "employee": "john doe",
                "balance": "1",
                "notes": "some more notes",
                "_id": "3"
            }
        ],
    }
}

You have the id, so you have to search for the relevant object, update it and pass it to the setNotes() setter.您有 id,因此您必须搜索相关对象,更新它并将其传递给setNotes() setter。

let localNotes = res.data.data.details.map((responseDetail) => {
    if (detail._id === id){
        let newNotes = [...responseDetail.notes, ...details];
        return {
            ...responseDetail,
            notes: newNotes
        };
    }
    return responseDetail;
});
if (localNotes.length){
    setNotes(localNotes);
}

Does this solve your problem?这能解决您的问题吗?

The answer was in the backend, the front end was fine, the code did not need any of the additions, it should just be:答案在后端,前端很好,代码不需要任何添加,它应该是:

const addBalHandler = (e) => {
    e.preventDefault();
    axios({
      method: "PUT",
      url: `http://localhost:5000/endpoint${id}`,
      data: {
        balance: total,
        notes: notes,
        date: date,
      },
    }).then((res) => {
      history.push(`/success/` + id);
      console.log(res.data);
    });
  };

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

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