Reputation: 1
I am trying to play around with the wikipedia API. I'm using Axios to make a request for the data. When I go to map through the prop passed through from App's state, I get the following error:
Uncaught TypeError: search.map is not a function
I have checked that the intended value is an array. It seems to be, I can manipulate it as such in the react dev tools console. It also has a proto of Array, so I'm confused as to why I can't do this.
Root Component:
class App extends React.Component
{
constructor()
{
super();
this.state = {search: {}}
this.wikiSearch();
}
wikiSearch()
{
axios
.get('https://en.wikipedia.org/w/api.php?action=opensearch&search="test"')
.then ((result) => {
result.data.shift();
this.setState({search: result.data});
});
}
render ()
{
return(
<div id="container">
<Header />
<SearchBar />
<SearchList search={this.state.search} />
</div>
);
}
}
export default App;
The component that uses state data from App
class SearchList extends React.Component
{
render()
{
let search = this.props.search;
search.map((element) => {
});
return(
<div id='SearchList'>
</div>
);
}
}
Upvotes: 0
Views: 1551
Reputation: 2711
You need to initialize search
as an empty array variable, not object, in your component state so that it's not throw erro on calling map
method on it like this:
this.state = {search: []}
not like this:
this.state = {search: {}}
Upvotes: 1