Last active
November 30, 2019 18:05
-
-
Save maxguzenski/f23f7bba4c726ea5956b17fd3917fa1c to your computer and use it in GitHub Desktop.
A first apollo graphql test with React Hooks... it is working ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what in the useAppContext file ? @maxguzenski