Reputation: 101
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>
Upvotes: 3
Views: 3502
Reputation: 322
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.
Upvotes: 0
Reputation: 202605
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)]
})
);
};
Upvotes: 2