Skip to content

Instantly share code, notes, and snippets.

@stivsk
Last active July 25, 2022 23:34
Show Gist options
  • Save stivsk/44854eb08884cb7d876c8e549afaa343 to your computer and use it in GitHub Desktop.
Save stivsk/44854eb08884cb7d876c8e549afaa343 to your computer and use it in GitHub Desktop.
Lazy SWR hook for GraphQL requests, compatible with Suspense
import useSWR from 'swr'
import { useState } from 'react'
import request from 'graphql-request'
import _ from 'lodash'
// GraphQL fetcher for SWR hook
export const graphqlFetcher = (query, variables) => request('http://localhost:4000/api/graphql', query, variables)
export const useLazySWR = (query) => {
// We're going to use SWR conditional fetching,
// so we have to set the trigger for the request.
const [variables, setVariables] = useState()
// Using "variables", we say SWR when to make the request.
const { data } = useSWR(variables && [query, variables], graphqlFetcher, { suspense: true })
// This promise function will allow us to access the lazy hook.
const executeQuery = (parameters) => new Promise((resolve, reject) => {
// Reject the promise if has the same parameters.
if (_.isEqual(parameters, variables)) reject(new Error('Requested twice with the same parameters'))
// Set the variables to make the request.
setVariables({ ...parameters })
// Resolve the promise.
resolve()
})
return [executeQuery, data]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment