to perform multiple dependent mutation - grandstack apollo graphql 3.3

1.5k Views Asked by At

I've a bit of confusion how to perform multiple mutation in graphql.

I've read articles about using of graphql() function or compose() function, but i haven't understood if these are the legacy way to do it (version 2) or is still a valid way to proceed.

I'm currently using apollo 3.3 with grandstack and in my component i do the following to perform a mutation (i used useMutation() hook provided by ApolloClient)

const CreateFBUser = gql `
  mutation CreateFBUser($name: String, $fbId: String!) {
    CreateFBUser(name: $name, fbId: $fbId) {
        _id
        id
        fbId
        name
    }
  }
`

function FbUserForm() {

    const { id } = useParams()
    const [formState, setFormState] = useState({})
    
    const [createFBUser,{data: createData}] = useMutation(CreateFBUser)

    const { loading, error, data } = useQuery(FBUser,{
        variables: {_id: id}
    }); 
    ...
    ..
    .
    

as you can see, i havent used components like <Query>, and so on..

FIRST QUESTION: is this component related to the apollo old version? are still regulary used or useMutation() hook is the first choice in apollo 3?

SECOND QUESTION: i need to perform a second mutation related to the first, and i need the generated id from the first mutation to execute the second

//the first mutation
const CreateFBUser = gql `
  mutation CreateFBUser($name: String, $fbId: String!) {
    CreateFBUser(name: $name, fbId: $fbId) {
        _id
        id
        fbId
        name
    }
  }
`

//the second mutation (pseudocode)
const AddFBUserMemberOf = gql`  
    mutation AddFBUserMemberOf($from: _GroupInput!, $to: _FBUserInput!) {
        AddFBUserMemberOf(from: $from, to: $to) {
            from
            to
        }
    }
`

moreover, the second mutation should be performed conditionally according to a value/a variable/something else

1

There are 1 best solutions below

0
On

The render prop components are deprecated and will not receive further updates or bug fixes according to the docs

For your second question; the mutation function returned from useMutation takes an onCompleted property in the options parameter that executes after the mutation successfully completes.

const [createFBUser,{data: createData}] = useMutation(CreateFBUser)
const [addFBUserMemberOf] = useMutation(AddFBUserMemberOf)

createFBUser({
  variables: {
    //...
  },
  onCompleted: (data) => {
    // data contains the result of createFBUser
    addFBUserMemberOf({
      variables: {
        //...
      }
    })
  }
})