Skip to content

Support for a Provider, useMutation, and useQuery

Compare
Choose a tag to compare
@alex-cory alex-cory released this 20 Jun 07:39
b912f72

Provider, useMutation, and useQuery

Provider using the GraphQL useMutation and useQuery

The Provider allows us to set a default url, options (such as headers) and so on.
There is array and object destructuring for useMutation and useQuery.

Query for todos

import { Provider, useQuery, useMutation } from 'use-http'

function QueryComponent() {
  const request = useQuery(`
    query Todos($userID string!) {
      todos(userID: $userID) {
        id
        title
      }
    }
  `)

  const getTodosForUser = id => request.query({ userID: id })
  
  return (
    <>
      <button onClick={() => getTodosForUser('theUsersID')}>Get User's Todos</button>
      {request.loading ? 'Loading...' : <pre>{request.data}</pre>}
    </>
  )
}

Add a new todo

This uses array destructuring, but it can also use object destructuring. The useMutation and useQuery are very similar to the usePost's array and object destructuring.

function MutationComponent() {
  const [todoTitle, setTodoTitle] = useState('')
  
  const [data, loading, error, mutate] = useMutation(`
    mutation CreateTodo($todoTitle string) {
      todo(title: $todoTitle) {
        id
        title
      }
    }
  `)
  
  const createtodo = () => mutate({ todoTitle })

  return (
    <>
      <input onChange={e => setTodoTitle(e.target.value)} />
      <button onClick={createTodo}>Create Todo</button>
      {loading ? 'Loading...' : <pre>{data}</pre>}
    </>
  )
}

Fetch more todos

function FetchComponent() {
  const request = useFetch('/todos')
  
  return (
    <>
      <button onClick={request.get}>Get Todos</button>
      {request.loading ? 'Loading...' : <pre>{request.data}</pre>}
    </>
  )
}

Provider

These props are defaults used in every request inside the <Provider />. They can be overwritten individually

function App() {

  const options = {
    headers: {
      Authorization: 'Bearer:asdfasdfasdfasdfasdafd'
    }
  }
  
  return (
    <Provider url='http://example.com' options={options}>
      <QueryComponent />
      <MutationComponent />
      <FetchComponent />
    <Provider/>
  )
}