Created
January 10, 2020 12:07
-
-
Save lucis/53609b12bf69bd89206c04eaa62897c6 to your computer and use it in GitHub Desktop.
Example of a custom Hook
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
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