简体   繁体   中英

React JS - I'm having difficult to get JSON informations from API on a Select box in my project

I'm new to React and JSON stuff, so I'm having some trouble to get JSON information and put it on an Option tag inside the Select on my project. What am I doing wrong?

Here's my code:

    componentWillMount() {
        this.fetchData();
      }

      fetchData() {
        fetch("https://grupoprever-api.qap/listas/estados", { mode: "cors" })
          .then(response => response.json())
          .then(parsedJSON => {
            parsedJSON.map(estado => ({
              v: `${estado.key}`,
              d: `${estado.value}`
            }));
          })

          .then(estados =>
            this.setState({
              estados
            })
          )

          .catch(error => console.log("Erro no Fetch:", error));
      }

And I'm trying to put this information in here:

    <div className="meioCampo">
              <span>Estado:</span>
              <select
                id="estadosDropdown"
                onChange={e => this.setState({ escolhidoEstado: e.target.value })}
              >
                {this.state.estados.map(estado => {
                  return (
                    <option key={estado.v} value={estado.v}>
                      {estado.d}
                    </option>
                  );
                })}
              </select>
            </div>

All of this are inside a Component.

Oh, my JSON data is like this:

{

    "AC":"Acre",
    "AL":"Alagoas",
    "AM":"Amaz\u00f4nia"

}

You're not returning any data from a map function.

change

.then(parsedJSON => {
    parsedJSON.map(estado => ({
      v: `${estado.key}`,
      d: `${estado.value}`
    }));
 })

to

.then(parsedJSON => {
    return parsedJSON.map(estado => ({
      v: `${estado.key}`,
      d: `${estado.value}`
    }));
  })

EDIT:

Also please don't call your api from componentWillMount method. While your code might be working, this lifecycle method is already marked as UNSAFE and should be avoided. Call your fetch request from componentDidMount instead. Initialize default state of your Component like:

constructor(props) {
  super(props);
  ... // your other code in constructor

  this.state = {
     estados: null,
     // add other state variables here...
  }
}

and add a check for 'null' state to your render() method like so:

<div className="meioCampo">
  <span>Estado:</span>
  <select
    id="estadosDropdown"
    onChange={e => this.setState({ escolhidoEstado: e.target.value })}         >
      {this.state.estados && this.state.estados.map(estado => {
        return (
          <option key={estado.v} value={estado.v}>
            {estado.d}
          </option>
        );
      })}
 </select>
</div>

EDIT 2:

as your response body is an object (not list), then you can try to following code:

fetchData() {
  fetch("https://grupoprever-api.qap/listas/estados", { mode: "cors" })
    .then(response => response.json())
    .then(estados =>
       this.setState({
          estados
      })
    );

then generate your options list with Object.keys() method:

render() {
   ....
  const {estados} = this.state;

  return(
    <div className="meioCampo">
      <span>Estado:</span>
      <select
        id="estadosDropdown"
        onChange={e => this.setState({ escolhidoEstado: e.target.value })}         >
          {estados && Object.keys(estados).map(key => {
            return (
              <option key={key} value={key}>
                {estados[key]}
              </option>
            );
          })}
     </select>
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM