Timmy
Timmy

Reputation: 165

React.js fetch Giphy API

I'm building a search engine (with React.js), where I can look for GIPHY gifs, using their API. I'm new to React.js and i'm having some trouble getting this code right.

import React from 'react'; //react library
import ReactDOM from 'react-dom'; //react DOM - to manipulate elements
import './index.css';
import SearchBar from './components/Search';
import GifList from './components/SelectedList';

class Root extends React.Component { //Component that will serve as the parent for the rest of the application.

  constructor() {
    super();

    this.state = {
      gifs: []
    }
  }

  handleTermChange(term) {
    console.log(term);
    //---------------------->
    let url = 'http://api.giphy.com/v1/gifs/search?q=${term}&api_key=dc6zaTOxFJmzC';
    fetch(url).
    then(response => response.json()).then((gifs) => {
      console.log(gifs);
      console.log(gifs.length);
      this.setState({
        gifs: gifs
      });
    });//<------------------------- THIS CODE HERE
  };


  render() {
    return (
      <div>
        <SearchBar onTermChange={this.handleTermChange} />
        <GifList gifs={this.state.gifs} />
      </div>
    );
  }
}
ReactDOM.render( <Root />, document.getElementById('root'));

I get the following error in the console: Uncaught (in promise) TypeError: _this2.setState is not a function at eval (index.js:64) at

Any help is appreciated :) Thanks!

Upvotes: 2

Views: 1835

Answers (1)

Sua Morales
Sua Morales

Reputation: 916

this is not auto-bound in ES6 style syntax.

You have to bind in the constructor: ``` super();

this.state = {
    gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)```

or use arrow function syntax for the function in question: func = () => {};

For reference: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

Upvotes: 4

Related Questions