0

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>
    );
  }
}
1
  • Because the prop you transferred "search" which you set on App state is "Object", not an Array. Commented Nov 30, 2016 at 22:30

1 Answer 1

1

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: {}}
Sign up to request clarification or add additional context in comments.

1 Comment

why do you suggest initializing state inside componentWillMount? could you please justify? we had a discussion about that here stackoverflow.com/q/40828004/5069226

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.