use-cep

0.0.1 • Public • Published

use-cep

Travis npm package Coveralls

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>
  )
}

Package Sidebar

Install

npm i use-cep

Weekly Downloads

1

Version

0.0.1

License

MIT

Unpacked Size

8.22 kB

Total Files

4

Last publish

Collaborators

  • gsantiago