0.0.1 • Published 5 years ago

use-cep v0.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

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