如何使用 Apollo 中的 useMutation 进行变异

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

How to mutate with useMutation from Apollo

问题

我有一个graphQL查询,它提供了所有要在表单中显示的输入,并且我必须在输入上发生onChange事件时使用相同的查询来变更数据库。

我成功地创建了查询,并显示了所有的输入。

现在,我遇到了一个困难,即如何在输入新数据时重新发送我的查询。

我需要发送特定的id,以便我的后端理解它必须变更现有的文章,而不是创建新的。

有什么方法可以做到这一点吗?

这是我的form.service.tsx代码:

export const FORM = gql`
  mutation form($article: ArticleInput!) {
    form(annonce: $annonce) {
      article{
        id
      }
      formContent
    }
  }
`;

export const FormData = ({ children }) => {
  const [form, { data, loading, error }] = useMutation(
    form,
    {
      variables: {
        annonce: {
          idtype: 2,
          id: 0, // 我需要这个值是动态的
        },
      },
    },
  );

  useEffect(() => {
    form().then((res) => {
      if (res.data) {
        res.data.form.formContent = JSON.parse(
          res.data.form.formContent,
        );
      }
    });
  }, [form]);

  return children(data, loading, error);
};

然后我在form.tsx中将其用作包装器:

<FormData>
  {(data, loading) => {
    if (loading) return <>loading...</>;

    return (
      <>
        <Section3 dataToDisplay={data.groups} />
      </>
    );
  }}

最后,在我的表单的section3.tsx中:

const Section3 = ({ data }) => {
  const [typeDeBienSelected, setTypeDeBienSelected] = useState<Group>(
    data.find((item) => item.selected) ?? data[0],
  );

  return (
    <div className="hk-flex hk-flex-col hk-gap-8">
      <MyInputComponent
        list={typeDeBien ?? []}
        value={typeDeBienSelected}
        setValue={(e) => setTypeDeBienSelected(e)}
      />
    </div>
  );
};

export default Section3;

请注意,我已经将代码从HTML实体(&gt;&lt;)转换为正常的JSX格式,以便更容易阅读和理解。

英文:

I have a graphQL query that give me all inputs to display in a form, and I have to use the same query to mutate database when there is an onChange event on an input.

I managed to make the query, and to display all my inputs.

Now, i'm having difficulties to find how I can resend my query with new value when a data is entered.

I need to send the specific id to make my backend understand that it has to mutate the existing article instead of creating a new one.

Any idea how to do this ?

Here is my form.service.tsx:

export const FORM = gql`
  mutation form($article: ArticleInput!) {
    form(annonce: $annonce) {
      article{
        id
      }
      formContent
    }
  }
`;

export const FormData = ({ children }) =&gt; {
  const [form, { data, loading, error }] = useMutation(
    form,
    {
      variables: {
        annonce: {
          idtype: 2,
          id: 0, // I need this to be dynamic
        },
      },
    },
  );

  useEffect(() =&gt; {
    form().then((res) =&gt; {
      if (res.data) {
        res.data.form.formContent = JSON.parse(
          res.data.form.formContent,
        );
      }
    });
  }, [form]);

  return children(data, loading, error);
};

Then I use this as a wrapper in form.tsx :

&lt;FormData&gt;
      {(data, loading) =&gt; {
        if (loading) return &lt;&gt;loading...&lt;/&gt;;

        return (
          &lt;&gt;
            &lt;Section3 dataToDisplay={data.groups} /&gt;

And finaly, in section3.tsx of my form :

const Section3 = ({ data }) =&gt; {
  const [typeDeBienSelected, setTypeDeBienSelected] = useState&lt;Group&gt;(
    data.find((item) =&gt; item.selected) ?? data[0],
  );

  return (
    &lt;div className=&quot;hk-flex hk-flex-col hk-gap-8&quot;&gt;
      &lt;MyInputComponent
        list={typeDeBien ?? []}
        value={typeDeBienSelected}
        setValue={(e) =&gt; setTypeDeBienSelected(e)}
      /&gt;
  );
};

export default Section3;

答案1

得分: 1

以下是翻译好的部分:

在 FormData 组件中添加状态变量

在您的 FormData 组件中,让我们添加一个状态变量来跟踪 id 值,并将 setId 函数作为一个 prop 从 FormData 传递到 Section3.tsx 组件。

export const FormData = ({ children }) => {
  const [id, setId] = useState(0); // 用于跟踪 ID 的状态变量

  const [form, { data, loading, error }] = useMutation(
    FORM,
    {
      variables: {
        annonce: {
          idtype: 2,
          id: id, // 在这里使用动态 ID
        },
      },
    },
  );

  useEffect(() => {
    form().then((res) => {
      if (res.data) {
        res.data.form.formContent = JSON.parse(
          res.data.form.formContent,
        );
      }
    });
  }, [form]);

  return children(data, loading, error, setId); // 将 setId 函数作为 prop 传递
};

更新 Section3 组件中的 setValue 函数

Section3.tsx 中,更新 setValue 函数以调用 setId 函数并传递新的 ID

const Section3 = ({ data, setId }) => {
  const [typeDeBienSelected, setTypeDeBienSelected] = useState(
    data.find((item) => item.selected) ?? data[0],
  );

  const handleInputChange = (newValue) => {
    setTypeDeBienSelected(newValue);
    setId(newValue.id); // 在输入值更改时更新 ID
  };

  return (
    <div className="hk-flex hk-flex-col hk-gap-8">
      <MyInputComponent
        list={typeDeBien ?? []}
        value={typeDeBienSelected}
        setValue={handleInputChange} // 在这里传递更新后的函数
      />
    </div>
  );
};

export default Section3;
英文:

As I understand you want to dynamically send the ID for mutation when an input value changes.
Here is the steps you can follow to achieve this.

Add State Variable in FormData Component

In your FormData component, let's add a s state variable to track the id value and pass the setId function as a prop from FormData to Section3.tsx component.

export const FormData = ({ children }) =&gt; {
  const [id, setId] = useState(0); // State variable to track the ID

  const [form, { data, loading, error }] = useMutation(
    FORM,
    {
      variables: {
        annonce: {
          idtype: 2,
          id: id, // Use the dynamic ID here
        },
      },
    },
  );

  useEffect(() =&gt; {
    form().then((res) =&gt; {
      if (res.data) {
        res.data.form.formContent = JSON.parse(
          res.data.form.formContent,
        );
      }
    });
  }, [form]);

  return children(data, loading, error, setId); // Pass the setId function as a prop
};

Update setValue function in Section3 Component

In the Section3.tsx, update the setValue function to call the setId function and pass the new ID:

const Section3 = ({ data, setId }) =&gt; {
  const [typeDeBienSelected, setTypeDeBienSelected] = useState(
    data.find((item) =&gt; item.selected) ?? data[0],
  );

  const handleInputChange = (newValue) =&gt; {
    setTypeDeBienSelected(newValue);
    setId(newValue.id); // Update the ID when the input value changes
  };

  return (
    &lt;div className=&quot;hk-flex hk-flex-col hk-gap-8&quot;&gt;
      &lt;MyInputComponent
        list={typeDeBien ?? []}
        value={typeDeBienSelected}
        setValue={handleInputChange} // Pass the updated function here
      /&gt;
    &lt;/div&gt;
  );
};

export default Section3;

huangapple
  • 本文由 发表于 2023年6月5日 15:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404462.html
匿名

发表评论

匿名网友

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

确定