Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Created June 4, 2020 00:29
Show Gist options
  • Save leocavalcante/db8f30ba7c9f152c7d6d7664ec1f3341 to your computer and use it in GitHub Desktop.
Save leocavalcante/db8f30ba7c9f152c7d6d7664ec1f3341 to your computer and use it in GitHub Desktop.
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};
}
@leocavalcante
Copy link
Author

Example usage:

const {data: postalCodeData, loading: postalCodeLoading} = useCepPromise(cep, input.postalCode);

useEffect(() => {
  if (postalCodeData) {
    setInput({
      ...input,
      streetName: postalCodeData.street,
      city: postalCodeData.city,
      state: postalCodeData.state,
    });
  }
}, [postalCodeData])
<input disabled={postalCodeLoading} />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment