Skip to content

Instantly share code, notes, and snippets.

@luciancaetano
Created March 13, 2020 04:57
Show Gist options
  • Select an option

  • Save luciancaetano/773b98ff92db740c82a0bc73105a723c to your computer and use it in GitHub Desktop.

Select an option

Save luciancaetano/773b98ff92db740c82a0bc73105a723c to your computer and use it in GitHub Desktop.

Revisions

  1. luciancaetano created this gist Mar 13, 2020.
    32 changes: 32 additions & 0 deletions useCepPromise.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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];
    };