I'm trying to populate the options of a dropdown with all the titles from this API.
I'm trying to:
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>
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)]
})
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With