【问题标题】:How to get the mutation response?如何获得突变反应?
【发布时间】:2020-06-18 11:11:25
【问题描述】:

我在我的 reactjs 应用程序中成功地进行了这种突变,但我想获得 graphql 返回的响应,但在我的 reactjs 应用程序中,这可能吗?

反应代码:

import { useMutation } from "@apollo/react-hooks";      

const [addStoreToDB, { error }] = useMutation(addStoreMutation);

  if (error) {
    console.log("error:", error);
    return <p>Error :(</p>;
  }

  const handleSubmit = event => {
    event.preventDefault();
    dispatch(addStoreAction(newStore));
    addStoreToDB({
      variables: {
        name: newStore.name,
        address: newStore.address,
        description: newStore.description,
        phone: newStore.phone,
        picture1: newStore.picture1
      },
      refetchQueries: [{ query: getStoresQuery }]
    });
  };

在 GraphQL 中:

mutation {
  addStore (name:"Lorem ipsum", address:"Lorem ipsum", description:"Lorem Ipsum", phone:"555555", picture1:"https://lorem-ipsum") {
    id
  }
}

【问题讨论】:

标签: reactjs graphql react-hooks apollo-client react-apollo-hooks


【解决方案1】:
const [addStoreToDB, { error }] = useMutation(addStoreMutation
    {
      onCompleted: (data) => {
        console.log(data) // the response
      },
      onError: (error) => {
        console.log(error); // the error if that is the case
      },
    }
  );

【讨论】:

    【解决方案2】:

    useMutation 返回的mutation 函数是一个promise。所以你可以使用.then.catch

     addStoreToDB({...stuff})
         .then(response => {
          //handle response
          })
         .catch(err =>{
         //handle error
        })
    

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 2020-11-12
      • 2019-02-23
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多