Skip to content

Instantly share code, notes, and snippets.

@lucis
Created January 10, 2020 12:07
Show Gist options
  • Save lucis/53609b12bf69bd89206c04eaa62897c6 to your computer and use it in GitHub Desktop.
Save lucis/53609b12bf69bd89206c04eaa62897c6 to your computer and use it in GitHub Desktop.
Example of a custom Hook
const useShipping = (sellers: Seller[] = [], skuId: string) => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string>(null)
const [estimates, setEstimates] = useState<Sla[]>([])
const { culture } = useRuntime()
const client = useApolloClient()
const getEstimates = (postalCode: string) => {
setLoading(true)
setError(null)
client
.query({
query: getShippingEstimates,
variables: {
country: culture.country,
postalCode,
items: sellers.map(({ sellerId: seller }) => ({
quantity: '1',
id: skuId,
seller,
})),
},
})
.then(({ data: { shipping: shippingData } }) => {
const shipping = shippingData as Shipping
const infos = shipping.logisticsInfo
const slas = pluck('slas', infos)
setEstimates(flatten(slas))
})
.catch(error => {
setError(error.msg)
})
.finally(() => {
setLoading(false)
})
}
return { loading, estimates, getEstimates, error }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment