Get a zip code?

Asked

Viewed 648 times

-1

I’m having a hard time implementing a ZIP Code consultation on React What I wish to do and the user informs the ZIP code number in the field <input/> and automatically form fields are filled in.

What I need to do to populate the form with the ZIP code search and when trying to do it the way I implemented it presents the following error:

:3000/#/customer register:1 Access to fetch at 'https://viacep.com.br/ws/-/json/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource. If an Opaque Response serves your needs, set the request’s mode to 'no-Cors' to fetch the Resource with CORS disabled.viacep.com.br/Ws/-/json/:1 Failed to load Resource: net::ERR_FAILED

But the search is done despite the error.

handleChange = (event) => {
    const value = event.target.value;
    const name = event.target.name;    
    this.setState({ [name] : value })    
    this.buscarCep();
}

buscarCep() {
    if(this.state.cep.length < 9) {
        return;
    } else {
        fetch(`https://viacep.com.br/ws/${this.state.cep}/json/`)
        .then((res) => res.json())
        .then((data) => {
         this.state.uf = data.uf;
         this.state.cidade = data.localidade;
         this.state.uf = data.uf;
         this.state.bairro = data.bairro;
         this.state.logradouro = data.logradouro;
        });
    }
}

render( ){
    return (
        <Card>
            <div className="row">
                <div className="col-md-5">
                    <FormGroup id="inputCep" label="CEP: *" >
                        <InputMask id="inputCep"
                               className="form-control" 
                               name="cep"
                               mask="99999-999"
                               value={this.state.cep}
                               onChange={this.handleChange}/>
                    </FormGroup>
                </div>
            </div>

            <div className="row">
                <div className="col-md-12">
                    <FormGroup id="inputLogradouro" label="Logradouro:" >
                        <input type="text" id="inputLogradouro"
                               className="form-control" 
                               name="logradouro"
                               value={this.state.logradouro}
                               onChange={this.handleChange}  />
                    </FormGroup>
                </div>
            </div>

            <div className="row">
                <div className="col-md-12">
                    <FormGroup id="inputBairro" label="Bairro:" >
                        <input type="text" id="inputBairro"
                               className="form-control" 
                               name="bairro"
                               value={this.state.bairro}
                               onChange={this.handleChange}  />
                    </FormGroup>
                </div>
            </div>

            <div className="row">
                <div className="col-md-6">
                    <FormGroup id="inputCidade" label="Cidade:" >
                        <input type="text" id="inputCidade"
                               className="form-control" 
                               name="cidade"
                               value={this.state.cidade}
                               onChange={this.handleChange}  />
                    </FormGroup>
                </div>

                <div className="col-md-6">
                    <FormGroup id="inputUf" label="UF:" >
                        <input type="text" id="inputUf"
                               className="form-control" 
                               name="uf"
                               value={this.state.uf}
                               onChange={this.handleChange}  />
                    </FormGroup>
                </div>
            </div>
        </Card>
    }
}
  • worked out .....

1 answer

0

Problems:

  • When using the fetch need to specify its mode of operation that in your case and

    { mode: 'cors' }
    

    this object being the second parameter when the request verb is GET.

  • Another point is that the method was not used setState to change the old state to the new value object requested by fetch and also do not put the data of a direct object at the root of your this.state always create keys, because with this opens up to have new states in this component.

  • As reported in the question, you want a certain number of numbers to be typed (in case it is 8, fact described in the API) to trigger the search dynamically, it is worth remembering that the this.setState has a second parameter which is a function and in this function means that the state has already been changed with this this.state.data.cep already have all the numbers typed and can then use the function this.buscarCep() to check if you can already make your request, otherwise the status has not yet changed tiring problem by the lack of digits in this number.

I made a minimal example:

const dataInit = {
  cep: "",
  logradouro: "",
  complemento: "", 
  bairro: "",
  localidade: "",
  uf: "",
  ibge: "",
  gia: "",
  ddd: "",
  siafi: "",
}
class App extends React.Component {  
  constructor(props) {
    super(props);
    this.state = { 
      data: dataInit
    }
  }
  url = () => {
    return `http://viacep.com.br/ws/${this.state.cep}/json/`;
  }
  handleChange = (event) => {
      const value = event.target.value;
      const name = event.target.name;    
      this.setState({ [name] : value }, () => {      
        this.buscarCep();
      });
  }

  buscarCep() {
      if(this.state.cep.length < 8) {
          return;
      } else {      
           fetch(this.url(), {mode: 'cors'})
            .then((res) => res.json())
            .then((data) => {
                if (data.hasOwnProperty("erro")) {
                    this.setState({data: dataInit});
                    alert('Cep não existente');
                } else {
                    this.setState({data});
                }
            })
            .catch(err => consolelog(err));
      }
  }
    render() {
      return (
        <div>
          <label> Digite o cep:
            <input 
               name="cep" 
               maxlength={8}
               value={this.state.cep} 
               onChange={this.handleChange}
            />           
          </label>
          <div>Endereço/Rua: {this.state.data.logradouro}</div>
          <div>Complemento: {this.state.data.complemento}</div>
          <div>Bairro: {this.state.data.bairro}</div>
          <div>Cidade: {this.state.data.localidade}</div>
          <div>UF: {this.state.data.uf}</div>
          <div>IBGE: {this.state.data.ibge}</div>
          <div>Gia: {this.state.data.gia}</div>
          <div>DDD: {this.state.data.ddd}</div>
          <div>Siafi:{this.state.data.siafi}</div>
        </div>
      )
    }
  }
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.