简体   繁体   中英

React: Populating select dropdown options from an API Call

so I am trying to populate a select dropdown option menu with values returned from a GET call to my API. I currently have code that successfully returns a list of values based on a location that the user enters. I also have a dropdown menu created to display the results, but currently it is not working. I believe I may be incorrectly using state / setState.

Current Output

Essentially, if the user type '1449' in the textbox, the dropdown options should be 'PAAF' and 'EXLA'.

The API get call returns a list of carriers in string format, as such:

[
    "PAAF",
    "EXLA"
]

The code for the component:

import React from 'react';
import axios from 'axios';


export default class FetchCarrierList extends React.Component {

  state = {
    carriers: []
  }

  render() {

    function loadCarriers(url) {
      axios({
        method: "get",
        url: url
      }).then((response) => {
        let relCarriers = response.data;
        console.log(relCarriers);
        **this.setState({relCarriers});**
      }).catch((response) => {
        console.log(response);
        alert('Error communicating with server');
      });
    }

    function getData(val) {
      let location = val.target.value;
      let baseUrl = "http://localhost:6012/myAPI/carrier/getCarriersByLocation/" + location;
      if (location.length === 4) {
        loadCarriers(baseUrl);
      }
    }

    return <div className="editPro">
      <h1>Edit Pro Numbers</h1>
      <div id="carrierSelection">
        <input type="text" id="locationEntry" onChange={getData}></input>
        <select id="carrierDropDown">
          <option selected disabled>Select A Carrier</option>
          {this.state.carriers.map(option => <option key={option} value={option}>{option}</option>)}
        </select>
      </div>
    </div>
  }
}

Thank you for taking the time to read this, any help is appreciated.

Your state has one property which is carriers

state = {
  carriers: []
}

but when you set your state after the API response you set it to relCarriers

this.setState({relCarriers});

which doesn't exist on the state.
Instead, you should set it like this

this.setState({carriers: relCarriers});

Or you can rename the variable where you store response.data to, to carriers and then set it like this

let carriers = response.data;
this.setState({carriers});

The reason why it doesn't work with just relCarriers is because you are assigning the value with shorthand property assignment - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

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