Rony Aparicio
Rony Aparicio

Reputation: 33

TypeError: _this2.setState is not a function

I don't understand why i'm getting this error. How could i solve it and most importantly why am i getting it?

I'm getting the correct response back from the API but i also get the error right after a make a call.

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      movies: []
    };
  }

  videoSearch(term) {
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${APIkey}&query=${term}&page=1`)
      .then(response => this.setState({movies: response.data.results}))
      .catch(err => console.log(err))
  };


  render() {
    return (
      <div className="App">
        <SearchBar onSearchTermChange={this.videoSearch} />
      </div>
    );
  }
}

export default App;



import React, {Component} from 'react';


class SearchBar extends Component {
    constructor(props) {
        super(props);

        this.state = { term: "" };
    }

    render() {
        return (
        <div className="search-bar">
            <input
            value={this.state.term}
            onChange={event => this.onInputChange(event.target.value)}
            />
        </div>
        );
    }

    onInputChange(term) {
        this.setState({ term });
        this.props.onSearchTermChange(term);
    }
}

export default SearchBar;

Upvotes: 3

Views: 2598

Answers (2)

Vikash Agrawal
Vikash Agrawal

Reputation: 91

Adding bind in constructor works but can affect readability at times.

this.videoSearch = this.videoSearch.bind(this);

Instead, you can also make the videoSearch an arrow function.

videoSearch = term => {
  axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${APIkey}&query=${term}&page=1`)
    .then(response => this.setState({movies: response.data.results}))
    .catch(err => console.log(err))
};

Upvotes: 0

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36219

Wild guess base on a mass quantity of these type of questions :)

Try:

constructor(props) {
  super(props);

  this.state = {
      movies: []
  };

  this.videoSearch = this.videoSearch.bind(this);
} 

Tell me if it works. If not I'll delete the answer.

I suspect that this is called for a different object than your App component.

Upvotes: 3

Related Questions