Abhishek Konnur
Abhishek Konnur

Reputation: 529

error on fetching api in reactjs

I am fetching api using api key and data from input box , I am getting error array that query must be provided. I am able to get data from inputbox. Below is the code.

class App extends Component {
  constructor() {
    super()
    this.state = { movie: '', movieList: [] };
    this.onGetMovie = this.onGetMovie.bind(this);
  }

  onGetMovie(data) {
    this.setState({ movie: data });
    console.log("--------");
  }

  componentDidMount() {
    console.log("*************");
    fetch('https://api.themoviedb.org/3/search/movie?query=' + this.state.movie + '&api_key='+API_KEY)
      .then(res => res.json())
      .then(movieList => {
        this.setState({ movieList: movieList.results });
        console.log(movieList);
      })
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={icons} className="App-logo" alt="logo" />
          <h1 className="App-title">
            Movies<span className="secondary">Db</span>
          </h1>
        </header>

        <SearchBar handleToParent={this.onGetMovie} />
        <p>Parent : {this.state.movie}</p>

      </div>
    );
  }
}

export default App;

Upvotes: 0

Views: 394

Answers (1)

hsz
hsz

Reputation: 152294

movie located in component's state is not available yet for componentDidMount.

fetch should be invoked after onGetMovie is called (even by onGetMovie method) and you'll get all data required to perform the query.

Upvotes: 3

Related Questions