0

I have a below code that I am trying to populate the Dropdown select in the React Form.

My Render component:

<Form.Control as="select">
  {this.state.originCity.map(name => (
    <option key={name.CityName} value={name.CityCode}>
      {name.CityName}
    </option>
  ))}
</Form.Control>;

My data to the originCity is below:

console.log("Selected State for Origin: " + e.target.value);
axios
  .get(`http://localhost:3010/cityNames?name=${e.target.value}`)
  .then(response => {
    var arr = [];
    for (var i in response.data) {
      arr.push(response.data[i]);
    }
    this.setState({ originCity: arr });
  });

Data I am getting in console log is

     [  {CityName: "Albion", CityCode: 240020}
       {CityName: "Alma (e)", CityCode: 240031}
       {CityName: "Alpena (e)", CityCode: 240042}  ]

But I am receiving an error in browser as below:

Objects are not valid as a React child (found: object with keys {CityName, CityCode}). If you meant to render a collection of children, use an array instead.

Pavan
  • 985
  • 2
  • 15
  • 27
Shiva Nara
  • 81
  • 1
  • 2
  • 10
  • You may want to double check the structure of `this.state.originCity` you may be trying to map an object instead of an array. This post might be helpful https://stackoverflow.com/questions/33117449/invariant-violation-objects-are-not-valid-as-a-react-child – Emma Nov 04 '19 at 19:55
  • 1
    x2 what @Emma said. Are you sure originCity is always an array? That error usually happens when you have an object. [Codesandbox](https://codesandbox.io/s/sleepy-faraday-cfm0f), you can check an example here. – Nicolas Hevia Nov 04 '19 at 19:59
  • Your response.data is an array, try using [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) not [for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). – slynagh Nov 04 '19 at 20:04

1 Answers1

1

if you already getting an array then why for loop interation is nedded ? pass the array into state directly

axios
  .get(`http://localhost:3010/cityNames?name=${e.target.value}`)
  .then(response => {
let arr = response.data;
this.setState({originCity:arr})
Arpit Vyas
  • 2,118
  • 1
  • 7
  • 18