0

I'm doing this mutation successfully in my reactjs app, but I want to get the response graphql returns but in my reactjs app, is it possible?

React code:

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 }]
    });
  };

in GraphQL:

mutation {
  addStore (name:"Lorem ipsum", address:"Lorem ipsum", description:"Lorem Ipsum", phone:"555555", picture1:"https://lorem-ipsum") {
    id
  }
}
Lester Arévalo
  • 342
  • 1
  • 6
  • 12
  • 2
    It's certainly possible. This is covered pretty clearly in the documentation: https://www.apollographql.com/docs/react/data/mutations/. The `useMutation` hook does not automatically execute the mutation you pass it when the component renders. – rustyshackleford Mar 05 '20 at 18:41

2 Answers2

1

mutation function returned by useMutation is a promise. so you may use .then and .catch like

 addStoreToDB({...stuff})
     .then(response => {
      //handle response
      })
     .catch(err =>{
     //handle error
    })
vamshi krishna
  • 2,618
  • 1
  • 11
  • 18
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
      },
    }
  );
Lester Arévalo
  • 342
  • 1
  • 6
  • 12