Published on

React post dict include dict name

Authors
  • avatar
    Name
    Lif
    Twitter

When use react to post a request, I met a problem which leads a error.

{
  "medicineWithoutMid": {
    "name": "超级药品",
    "malias": "超级",
    "unit": "g",
    "description": "",
    "price": 34,
    "action": ""
  }
}

My backend only need the inner dictionary, but got a dict with variable name.

Actually my post function just like below:

  const handleSubmit = async () => {
    try {
      const { mid, ...medicineWithoutMid } = medicine;
      const response = await axios.post('/medical/api/v1/anagraph', {
        medicineWithoutMid 
        });
      console.log(response.data);
      setOpen(false);
    } catch (error) {
      console.error(error);
    }
  };

If I add extra braces around the medicineWithoutMid object when sending data, it actually creates a new object with the medicineWithoutMid property.

So, what I should do is to delete the braces.

Finally, my code is just like this:

  const handleSubmit = async () => {
    try {
      const { mid, ...medicineWithoutMid } = medicine;
      const response = await axios.post('/medical/api/v1/anagraph', 
        medicineWithoutMid
      );
      console.log(response.data);
      setOpen(false);
    } catch (error) {
      console.error(error);
    }
  };