Created
March 13, 2020 04:57
-
-
Save luciancaetano/773b98ff92db740c82a0bc73105a723c to your computer and use it in GitHub Desktop.
React Hook for cep-promise
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 cep from 'cep-promise'; | |
| import { useCallback, useState, useRef } from 'react'; | |
| interface ICEP { | |
| cep: string; | |
| state: string; | |
| city: string; | |
| street: string; | |
| neighborhood: string; | |
| } | |
| export const useCepPromise = () => { | |
| const [isLoading, setLoading] = useState(false); | |
| const [result, setResult] = useState<ICEP | null>(null); | |
| const [error, setError] = useState<Error | null>(null); | |
| const previoursSearch = useRef(''); | |
| const search = useCallback(async (text: string) => { | |
| setLoading(true); | |
| try { | |
| if (previoursSearch.current !== text) { | |
| previoursSearch.current = text; | |
| setResult(await cep(text)); | |
| } | |
| } catch (e) { | |
| setError(e); | |
| } | |
| setLoading(false); | |
| }, []); | |
| return [search, isLoading, result, error]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment