DEV Community

Ian Jones
Ian Jones

Posted on

2 1

Write a GraphQL Mutation using React Hooks with Urql

Watch "Write a GraphQL Mutation using React Hooks with Urql" (community resource) on egghead.

The first thing we need to do is import {useMutation} from 'urql'.

We will call the useMutation hook in our component. This hook returns an array with the result in the first slot and a function to execute the mutation in the second.

const App = () => {
  const [res, executeMutation] = useMutation()
}

Now we need to define a query that we are going to use. Here is the one I am going to use:

const addCourse = `
  mutation addCourse($slug: String!, $title: String!){
    insert_courses(objects: {slug: $slug, title: $title}) {
      returning {
        title
        slug
      }
    }
  }

This query takes a slug and a title as a string (they are both required). The Hasura api I am using defines are returning object. So we will grab the title and slug off of the returned object.

Now we can pass this query to our useMutation hook.

const [res, executeMutation] = useMutation(addCourse)

Lets wire up the wire up the execution method to a button. executeMutation takes an object with keys slug and title. These are the variables we defined in our GraphQL query earlier. We are going to log our res variable to see whats returned.

const App = () => {
  const [res, executeMutation] = useMutation(addCourse)
  console.log({ res })
  return (
    <button
      onClick={() => executeMutation({ title: 'My Course', slug: 'my-course' })}
    >
      Create Course
    </button>
  )
}
{res: {fetching: true, stale: false, error: undefined, data: undefined, extensions: undefined}}
{res: {fetching: false, stale: false, data: {}, error: undefined, extensions: undefined}}

You can see the result updates when the request starts and again when the query returns the data. This is what the data object looks like:

console.log(res.data)
{
  insert_courses: {
    returning: {
      slug: 'my-course',
      title: 'My Course'
    }
  }
}

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay