React
@unicep/react gives you the useCep hook, for React 18 or newer.
npm install @unicep/reactpnpm add @unicep/reactyarn add @unicep/reactbun add @unicep/react@unicep/core is installed with it.
import { useState } from 'react';import { useCep } from '@unicep/react';
export function CepField() { const [value, setValue] = useState(''); const { data, error, isLoading } = useCep(value);
return ( <> <input value={value} onChange={(e) => setValue(e.target.value)} placeholder="00000-000" /> {isLoading && <p>Searching…</p>} {error && <p>{error.message}</p>} {data && ( <p> {data.street}, {data.neighborhood} - {data.city}/{data.state} </p> )} </> );}The hook only looks up when the value is a valid CEP (with or without the hyphen), so you can wire it straight to a text field. If the CEP changes, the previous result is dropped and the in-flight request is cancelled.
useCep(cep: string | null | undefined, options?: { unicep?: Unicep; // default: shared instance with all built-in providers enabled?: boolean; // false pauses lookups, default true}): { data: Address | undefined; error: Error | undefined; isLoading: boolean; // true while a lookup for the current valid CEP is in flight}error is one of the unicep errors, such as CepNotFoundError or
AllProvidersFailedError.
Custom providers and options
Section titled “Custom providers and options”import { Unicep, viaCep, brasilApi } from '@unicep/core';
// Create it once, outside the component, so you do not lose the circuit breaker state.const unicep = new Unicep({ providers: [viaCep(), brasilApi()], timeoutMs: 3000, cache: {},});
const { data } = useCep(value, { unicep });