Skip to content

Instantly share code, notes, and snippets.

@maxguzenski
Last active November 30, 2019 18:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxguzenski/f23f7bba4c726ea5956b17fd3917fa1c to your computer and use it in GitHub Desktop.
Save maxguzenski/f23f7bba4c726ea5956b17fd3917fa1c to your computer and use it in GitHub Desktop.
A first apollo graphql test with React Hooks... it is working ;)
import {useCallback, useState} from 'react'
import useAppContext from './useAppContext'
const useMutation = ({ignoreResults=true, ...rest}) => {
const {client} = useAppContext()
const [result, setResult] = useState({
client,
data: {},
loading: false,
error: false
})
const mutate = useCallback(async (opts) => {
if (!ignoreResults) {
setResult(old => ({...old, loading: true}))
}
const {data, error} = await client.mutate({...rest, ...opts})
if (!ignoreResults) {
setResult(old => ({...old, data, error, called: true, loading: false}))
}
return {data, error}
})
result.mutate = mutate
return result
}
export default useMutation
import {useReducer} from 'react'
import useAppContext from './useAppContext'
function reducer(state, newState) {
return {...state, ...newState}
}
function useQuery({notifyOnNetworkStatusChange, ...params}) {
const {client} = useAppContext()
const [state, dispatch] = useReducer(reducer, {loading: true, data: {}, client})
const vars = Object.keys(params.variables).sort().reduce((list, k) => {
list.push(k)
list.push(params.variables[k])
return list
}, [])
React.useEffect(() => {
const resp = client.watchQuery(params)
const refetch = resp.refetch.bind(resp)
const fetchMore = resp.fetchMore.bind(resp)
const updateQuery = resp.updateQuery.bind(resp)
const subscribed = resp.subscribe(() => {
const {
networkStatus,
data,
error
} = resp.currentResult()
// (!partial || networkStatus === 7 || (networkStatus === 1 && data))
//if (data || error) {
if (networkStatus === 7 || notifyOnNetworkStatusChange) {
dispatch({
loading: networkStatus !== 7,
networkStatus,
data,
error,
refetch,
fetchMore,
updateQuery
})
}
})
return () => subscribed.unsubscribe()
}, [params.query, params.fetchPolicy || '', ...vars])
return state
}
export default useQuery
@tarex
Copy link

tarex commented Nov 18, 2018

what in the useAppContext file ? @maxguzenski

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment