How to populate dropdown with api data in React?

Viewed 1948

I'm trying to populate the options of a dropdown with all the titles from this API.

I'm trying to:

  • Save the titles into the titles : [] object
  • Map all those titles into separate elements

But I'm getting the error

Unhandled Rejection (TypeError): Cannot convert undefined or null to object

Can somebody point me in the right direction?

    import React from "react"
import Header from "./Header"
import CardContent from "./CardContent"
import axios from "axios";

class CardContainer extends React.Component {
  state = {
    display: [],
    titles: []
  };

  componentWillMount = (e) => {
    axios.get("https://ghibliapi.herokuapp.com/films")
      .then(response => this.setState({
        titles: response.data[Object.keys(response.data.title)],
        display: response.data[Math.floor(Math.random() * response.data.length)]
      }))
  }

  render() {
    return (
      <div className="container">
        <Header />
        <select>
          {this.state.titles.map(title => (
            <option key={title} value={title}>
              {title}
            </option>
          ))}
        </select>    
2 Answers

You should really use componentDidMount to do the data fetch, but the main issue is that you appear to want an array of all the titles, so you need to map over the response data and create this array.

componentDidMount = (e) => {
  axios.get("https://ghibliapi.herokuapp.com/films").then((response) =>
    this.setState({
      titles: response.data.map(({ title }) => title), // <-- map titles
      display: response.data[Math.floor(Math.random() * response.data.length)]
    })
  );
};

Edit how-to-populate-dropdown-with-api-data-in-react

You are getting the error as "Unhandled Rejection (TypeError): Cannot convert undefined or null to object" because response.data is an array. Object.key() can be only applied to objects. Try map() function to extract the objects one by one.

Related