1

Here's my code :

class App extends Component {
  state = {
    query: '',
    results: []
  }
  handleSearch(e) {
    var query = e.target.elements.query.value;
   axios.get("http://www.omdbapi.com/?s=" + query + "&page=1&apikey=xxxx")
      .then(function (response) {
        console.log(response.data);
        this.setState({
          results: response.data.Search
        });
      }.bind(this))
      .catch(function (error) {
      });
    e.preventDefault();
  }

I'm trying to fetch data from omdb and show it on page.

the problem is setState not updating an array results?

Any idea ? Thanks

10
  • 1
    If you write console.error(error); inside your catch function, does it log anything to the console? Do you get an error in the Network tab of your Developer Tools? Commented Nov 11, 2018 at 21:55
  • @Tholle yes ; the output is "TypeError: Cannot read property 'setState' of undefined " Commented Nov 11, 2018 at 22:02
  • @Axnyff but I just bind it with .bind(this) Commented Nov 11, 2018 at 22:02
  • @Chino Alright. Then you most likely need to bind handleSearch to this in the constructor, or make handleSearch into a class property arrow function: handleSearch = (e) => { ... }; Commented Nov 11, 2018 at 22:03
  • 1
    Thank you so much guys, you can write it as answer if you want. Commented Nov 11, 2018 at 22:15

1 Answer 1

1

You bind the function called when the axios requests completes correctly, but you must also bind the handleSearch method itself. You could do this in the constructor, or use a class property arrow function instead:

class App extends Component {
  state = {
    query: '',
    results: []
  }

  handleSearch = (e) => {
    // ...
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.