Last active
October 15, 2020 05:19
-
-
Save danielkcz/1d3a62d6831aaedf5f34b12d9b2f287d to your computer and use it in GitHub Desktop.
useQuery + useContext
This file contains hidden or 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 { useQuery } from 'react-apollo-hooks' | |
const RandomGiphy = () => { | |
const { tag } = useSettings() | |
const { data } = useQuery( | |
RandomGiphyQuery, { | |
variables: { tag } | |
} | |
} | |
// handle loading & error states... | |
return <img src={data.giphy.random.url} /> | |
} |
This file contains hidden or 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 React from 'react' | |
const context = React.createContext() | |
export const SettingsProvider = ({ children }) => { | |
// useReducer could be better candidate for a more complex scenarios | |
const [settings, updateSettings] = React.useState({ tag: 'kittens' }) | |
return ( | |
<context.Provider value={{ data: settings, update: updateSettings }}> | |
{children} | |
</context.Provider> | |
) | |
} | |
// hook to consume data only | |
export const useSettings = () => { | |
return React.useContext(context).data | |
} | |
// hook to get update callback (or dispatch) | |
export const useSettingsUpdate = () => { | |
return React.useContext(context).update | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment