Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate dropdown with api data in React?

Tags:

reactjs

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>    
like image 503
esvnt Avatar asked Nov 23 '25 22:11

esvnt


1 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

like image 140
Drew Reese Avatar answered Nov 25 '25 18:11

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!