apollo v3 mutations code example

Example 1: usemutation apollo

import { gql, useMutation } from '@apollo/client';

const ADD_TODO = gql`
  mutation AddTodo($type: String!) {
    addTodo(type: $type) {
      id
      type
    }
  }
`;


function AddTodo() {
  let input;
  const [addTodo, { data }] = useMutation(ADD_TODO);

  return (
    
{ e.preventDefault(); addTodo({ variables: { type: input.value } }); input.value = ''; }} > { input = node; }} />
); }

Example 2: apollo graphql mutation hook

const UPDATE_TODO = gql`
  mutation UpdateTodo($id: String!, $type: String!) {
    updateTodo(id: $id, type: $type) {
      id
      type
    }
  }
`;

function Todos() {
  const { loading, error, data } = useQuery(GET_TODOS);
  const [updateTodo] = useMutation(UPDATE_TODO);

  if (loading) return 

Loading...

; if (error) return

Error :(

; return data.todos.map(({ id, type }) => { let input; return (

{type}

{ e.preventDefault(); updateTodo({ variables: { id, type: input.value } }); input.value = ''; }} > { input = node; }} />
); }); }

Tags:

Misc Example