use-cep
v0.0.1
Published
use-cep React component
Downloads
4
Maintainers
Readme
use-cep
A React hook for loading CEP data. It uses cep-promise
under the hood.
Installation
npm install use-cep
yarn add use-cep
Usage
import useCep from 'use-cep'
// Using the hook
const { fetch, loading, error, data } = useCep()
Here's an example with react-final-form
:
import React from 'react'
import { Form, Field } from 'react-final-form'
import useCep from 'use-cep'
function App (props) {
const { fetch, loading, error, data } = useCep()
return (
<Form {...props}>
{({ handleSubmit, form }) => (
<form onSubmit={handleSubmit}>
<Field
name='cep'
placeholder='CEP'
>
{({ input, meta, ...props }) => (
<input
{...input}
{...props}
onChange={e => {
if (e.target.value.length === 8) {
fetch(e.target.value).then(data => {
form.batch(() => {
Object.keys(data).forEach(key => {
form.change(key, data[key])
})
})
})
}
input.onChange(e)
}}
/>
)}
</Field>
<Field
name='state'
component='input'
placeholder='State'
disabled={loading}
/>
<Field
name='city'
component='input'
placeholder='City'
disabled={loading}
/>
<Field
name='neighborhood'
component='input'
placeholder='Neighborhood'
disabled={loading}
/>
</form>
)}
</Form>
)
}