如何获得突变反应?

时间:2020-03-05 18:23:29

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

我已经在我的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
  }
}

2 个答案:

答案 0 :(得分:0)

useMutation返回的

变异函数是一个承诺。因此您可以像

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

答案 1 :(得分:0)

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