首页 > 解决方案 > 如何访问 Apollo 的 useMutaion 响应

问题描述

当我使用 useMutation 挂钩进行突变时,我可以控制台记录我的数据,但我无法将数据对象保存在 localState 中。我不知道我错过了什么。任何帮助表示赞赏。

我的代码如下:

//Schema file

startTest(identifier: String): TestResponse

突变有效载荷如下:

  type TestResponse {
    errorCode: Int
    errorMessage: String
    success: Boolean
    transactionId: ID
    version: Int
  }

在解析器中,我硬编码了以下数据返回:

    startTest(_, { identifier }) {
      console.log("hello from server");
      return {
        errorCode: 0,
        errorMessage: null,
        success: true,
        transactionId: "d2984911-bbc4-4e6a-9103-96ca934f6ed3",
        version: 0,
      };
    },

在组件文件夹中,我通过单击按钮触发了突变。

const [startTestt, { loading, error, data }] = useMutation(
    START_FIRE_DAMPER_TEST,
    {
      onCompleted: ({ startFireDampersTest }) =>
        console.log(startFireDampersTest.success),
        useState(startFireDampersTest.success)
       
    },

    {
      onError: () => console.log("error!"), // never gets called
    }
  );

  console.log(result); // undefined

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error!</p>;

  if (data && data.startFireDampersTest)
    return (
      <div>
        <p>Success!</p>
        <pre>{JSON.stringify(data, null, 2)}</pre> // I can see string object but how to render the element of the object inside the component??
      </div>
    );


  const triggerTest = () => {
    startTest({ variables: { identifier: "0000000" } });
  };

  return (
    <>
      <Banner />
       <button onClick={triggerTest}>Click to Delete Buck</button>

    </>
  );

我需要访问从突变返回的返回数据以供以后使用。测试响应/有效负载与要更新的任何其他查询或类型无关。它只包含测试的状态和我需要保存在本地状态或可能在组件中呈现它的其他关键值。

标签: graphapolloreact-apollo

解决方案


You already have a useState inside your onCompleted, you'd just need to write properly. Assuming the useState is a call to the a React's useState hook, then you're probably just need to move the initialization of your state to your component.

const [isSuccess, setIsSuccess] = useState(false);
const [startTestt, { loading, error, data }] = useMutation(
    START_FIRE_DAMPER_TEST,
    {
      onCompleted: ({ startFireDampersTest }) =>
        console.log(startFireDampersTest.success),
        setIsSuccess(startFireDampersTest.success)
       
    },
    {
      onError: () => console.log("error!"), // never gets called
    }
  );

推荐阅读