Created
June 4, 2020 00:29
-
-
Save leocavalcante/db8f30ba7c9f152c7d6d7664ec1f3341 to your computer and use it in GitHub Desktop.
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 {useEffect, useState} from "react"; | |
interface CEP { | |
cep: string, | |
state: string, | |
city: string, | |
street: string, | |
neighborhood: string | |
} | |
type CepPromiseClient = (cep: string | number) => Promise<CEP> | |
export function useCepPromise(client: CepPromiseClient, postalCode: string | undefined | null) { | |
const [loading, setLoading] = useState(false); | |
const [data, setData] = useState<CEP | undefined>(); | |
const [error, setError] = useState<Error | undefined>(); | |
useEffect(() => { | |
const value = postalCode?.replace(/\D/g, ''); | |
if (value && value.length === 8) { | |
setLoading(true); | |
client(value) | |
.then(data => setData(data)) | |
.catch(error => setError(error)) | |
.finally(() => setLoading(false)); | |
} | |
}, [postalCode]); | |
return {loading, data, error}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: