错误 400 请求无效,与 React 和 RTKQ 中的表单有关。

huangapple go评论110阅读模式
英文:

error 400 bad request with form in react and RTKQ

问题

以下是您要翻译的内容:

"i have a form that i want to add or update an item with it. for both adding and updating i use POST request. if i have a id param in my url i want to update the item and if there is no id i want to add item. for adding every thing works fine but when i want to update i got 400 bad request that says some of my form data are required. i used same structure for my form data in adding item that worked fine."

import Button from "@/components/utils/button/button.component";
import { InputController } from "@/components/utils/input/input-controller.component";
import Modal from "@/components/utils/modal/modal.component";
import { TextAreaController } from "@/components/utils/textarea/textarea-controller.component";
import {
  useAddComplianceRequirementMutation,
  useGetComplianceRequirementByIdQuery,
  useUpdateComplianceRequirementMutation,
} from "@/infrastructure/slice/compliance-requirement.slice";
import { useForm } from "react-hook-form";
import { useParams } from "react-router-dom";

type Props = {
  onClose: () => void;
};
const AddRequirementsGroupModal: React.FC<Props> = ({ onClose }) => {
  const { control, handleSubmit } = useForm();
  const { complianceId, id } = useParams();

  const [addRequirement, { isLoading: isAddLoading }] =
    useAddComplianceRequirementMutation();
  const [updateComplianceRequirement, { isLoading: isUpdateLoading }] =
    useUpdateComplianceRequirementMutation();

  const { data: groupData, isLoading } = useGetComplianceRequirementByIdQuery(
    { id },
    { skip: !id }
  );

  const onSubmit = handleSubmit(async (data) => {
    const sendData = {
      ...data,
      packageId: complianceId,
      type: 1,
      complianceId,
    };
    try {
      if (id) {
        await updateComplianceRequirement({
          ...sendData,
          id,
        });
        onClose();
      } else {
        await addRequirement(sendData);
        onClose();
      }
    } catch (e) {
      console.log(e);
    }
  });

  return (
    <>
      <Modal
        isOpen
        onClose={onClose}
        title="اضافه کردن گروه الزامات"
        isLoading={isLoading}
      >
        <form onSubmit={onSubmit}>
          <InputController
            control={control}
            name="label"
            label="عنوان گروه الزامات"
            requiredInput
            rules={{ required: "لطفا عنوان گروه الزامات را وارد کنید." }}
            defaultValue={groupData?.label}
          />
          <TextAreaController
            control={control}
            name="title"
            defaultValue={groupData?.title}
          />
          <div className="flex gap-2">
            <InputController
              control={control}
              name="value"
              label="وزن گروه الزامات"
              requiredInput
              rules={{ required: "لطفا وزن گروه الزامات را وارد کنید." }}
              type="number"
              defaultValue={groupData?.value}
            />
            <InputController
              control={control}
              name="code"
              label="کد"
              requiredInput
              rules={{ required: "لطفا فصل گروه الزامات را مشخص کنید." }}
              defaultValue={groupData?.code}
            />
          </div>
          <TextAreaController
            control={control}
            name="description"
            label="توضیحات گروه الزامات"
            defaultValue={groupData?.description}
          />
          <div className="flex justify-start gap-2">
            <Button size="sm" loading={isAddLoading || isUpdateLoading}>
              ثبت گروه
            </Button>
            <Button color="danger" onClick={onClose}>
              انصراف
            </Button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default AddRequirementsGroupModal;

"and if it helps here are my add request:"

addComplianceRequirement: builder.mutation({
  query: (body) => ({
    url: "/packageitem",
    method: "POST",
    body,
  })
})

"and this is my update request :"

updateComplianceRequirement: builder.mutation({
  query: ({ id, body }) => ({
    url: `/packageitem/${id}`,
    method: 'POST',
    body,
  })
})
英文:

i have a form that i want to add or update an item with it. for both adding and updating i use POST request. if i have a id param in my url i want to update the item and if there is no id i want to add item. for adding every thing works fine but when i want to update i got 400 bad request that says some of my form data are required. i used same structure for my form data in adding item that worked fine.

import Button from &quot;@/components/utils/button/button.component&quot;;
import { InputController } from &quot;@/components/utils/input/input-controller.component&quot;;
import Modal from &quot;@/components/utils/modal/modal.component&quot;;
import { TextAreaController } from &quot;@/components/utils/textarea/textarea-controller.component&quot;;
import {
useAddComplianceRequirementMutation,
useGetComplianceRequirementByIdQuery,
useUpdateComplianceRequirementMutation,
} from &quot;@/infrastructure/slice/compliance-requirement.slice&quot;;
import { useForm } from &quot;react-hook-form&quot;;
import { useParams } from &quot;react-router-dom&quot;;
type Props = {
onClose: () =&gt; void;
};
const AddRequirementsGroupModal: React.FC&lt;Props&gt; = ({ onClose }) =&gt; {
const { control, handleSubmit } = useForm();
const { complianceId, id } = useParams();
const [addRequirement, { isLoading: isAddLoading }] =
useAddComplianceRequirementMutation();
const [updateComplianceRequirement, { isLoading: isUpdateLoading }] =
useUpdateComplianceRequirementMutation();
const { data: groupData, isLoading } = useGetComplianceRequirementByIdQuery(
{ id },
{ skip: !id }
);
const onSubmit = handleSubmit(async (data) =&gt; {
const sendData = {
...data,
packageId: complianceId,
type: 1,
complianceId,
};
try {
if (id) {
await updateComplianceRequirement({
...sendData,
id,
});
onClose();
} else {
await addRequirement(sendData);
onClose();
}
} catch (e) {
console.log(e);
}
});
return (
&lt;&gt;
&lt;Modal
isOpen
onClose={onClose}
title=&quot;اضافه کردن گروه الزامات&quot;
isLoading={isLoading}
&gt;
&lt;form onSubmit={onSubmit}&gt;
&lt;InputController
control={control}
name=&quot;label&quot;
label=&quot;عنوان گروه الزامات&quot;
requiredInput
rules={{ required: &quot;لطفا عنوان گروه الزامات را وارد کنید.&quot; }}
defaultValue={groupData?.label}
/&gt;
&lt;TextAreaController
control={control}
name=&quot;title&quot;
defaultValue={groupData?.title}
/&gt;
&lt;div className=&quot;flex gap-2&quot;&gt;
&lt;InputController
control={control}
name=&quot;value&quot;
label=&quot;وزن گروه الزامات&quot;
requiredInput
rules={{ required: &quot;لطفا وزن گروه الزامات را وارد کنید.&quot; }}
type=&quot;number&quot;
defaultValue={groupData?.value}
/&gt;
&lt;InputController
control={control}
name=&quot;code&quot;
label=&quot;کد&quot;
requiredInput
rules={{ required: &quot;لطفا فصل گروه الزامات را مشخص کنید.&quot; }}
defaultValue={groupData?.code}
/&gt;
&lt;/div&gt;
&lt;TextAreaController
control={control}
name=&quot;description&quot;
label=&quot;توضیحات گروه الزامات&quot;
defaultValue={groupData?.description}
/&gt;
&lt;div className=&quot;flex justify-start gap-2&quot;&gt;
&lt;Button size=&quot;sm&quot; loading={isAddLoading || isUpdateLoading}&gt;
ثبت گروه
&lt;/Button&gt;
&lt;Button color=&quot;danger&quot; onClick={onClose}&gt;
انصراف
&lt;/Button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/Modal&gt;
&lt;/&gt;
);
};
export default AddRequirementsGroupModal;

and if it helps hera are my add request:

 addComplianceRequirement: builder.mutation({
query: (body) =&gt; ({
url: &quot;/packageitem&quot;,
method: &quot;POST&quot;,
body,
})

and this is my update request :

 updateComplianceRequirement: builder.mutation({
query: ({ id, body }) =&gt; ({
url: `/packageitem/${id}`,
method: &#39;POST&#39;,
body,
})

答案1

得分: 0

这里的问题是...

await updateComplianceRequirement({
...sendData,
id,
});

这将创建一个像这样的有效载荷

{
"id": 1,
"code": "some code",
"label": "some label",
...
}

但是你的 updateComplianceRequirement 变异正在寻找一个具有两个属性的对象; idbody

只需在构建有效载荷时将 sendData 放入 body 属性中

await updateComplianceRequirement({ id, body: sendData });

或者更改你的变异为类似以下内容

updateComplianceRequirement: builder.mutation({
query: ({ id, ...body }) => ({ // 将其余部分展开到 `body`
url: `/packageitem/${id}`,
method: 'POST',
body,
})
英文:

The problem is here...

> lang-js
&gt; await updateComplianceRequirement({
&gt; ...sendData,
&gt; id,
&gt; });
&gt;

This will create a payload like

{
&quot;id&quot;: 1,
&quot;code&quot;: &quot;some code&quot;,
&quot;label&quot;: &quot;some label&quot;,
...
}

but your updateComplianceRequirement mutation is looking for an object with two properties; id and body.

Simply place the sendData into a body property when constructing the payload

await updateComplianceRequirement({ id, body: sendData });

or change your mutation to something like

updateComplianceRequirement: builder.mutation({
query: ({ id, ...body }) =&gt; ({ // spread the rest into `body`
url: `/packageitem/${id}`,
method: &#39;POST&#39;,
body,
})

huangapple
  • 本文由 发表于 2023年7月11日 14:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76659301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定