Ishan Patel
Ishan Patel

Reputation: 6091

Getting an arrow function syntax error in React

I have following code which is rendering the React app.

import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list'

const API_KEY = 'AIzaSyCF7K58Xwpr7m5C0yGy8Bck02iQ0fJ2yuI';


class App extends React.Component {

  constructor(props){

    super(props);

    this.state = {videos: []};

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

  YTSearch({key: API_KEY, term: BMW}, (videos => {
    this.setState({ videos });
  });
);

  render() {
    return (
      <div>
        <SearchBar />
        <VideoList videos={ this.state.videos }/>
      </div>
    );
  }
}


ReactDOM.render(<App />, document.querySelector('.container'));

Also I think I have some syntax problem with using the setState function.

Upvotes: 2

Views: 268

Answers (3)

Prakash Sharma
Prakash Sharma

Reputation: 16472

Class body is for defining functions and variables but you are calling the function YTSearch inside class body, which is giving syntax error. If you want to call the function then either call it inside constructor or inside any other function like componentDidMount etc

constructor(props){
    super(props);
    this.state = {videos: []};
  }

componentDidMount(){
   // Call it here inside componentDidMount or any other function
    YTSearch({key: API_KEY, term: BMW}, (videos => {
      this.setState({ videos });
    }));
}

Upvotes: 1

Jenna Rajani
Jenna Rajani

Reputation: 243

Your specific issue isn't made clear in your question but from looking at your code I assume your YTSearch is never firing and therefore your state never gets set with a list of videos.

If you are trying to create a method to pass to the search bar that triggers a search perhaps try something like this. I hope this helps!

import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list';

const API_KEY = 'AIzaSyCF7K58Xwpr7m5C0yGy8Bck02iQ0fJ2yuI';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = { videos: [] };

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

  search(phrase) {
    YTSearch({ key: API_KEY, term: phrase }, videos => {
      this.setState({ videos });
    });
  }

  render() {
    return (
      <div>
        <SearchBar onSearch={this.search}/>
        <VideoList videos={this.state.videos} />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('.container'));

Upvotes: 0

cay cospete
cay cospete

Reputation: 33

Your destructured setState is fine, you have a bracket (open which needs to be closed or either way you can remove it as there is only one argument in your arrow function.

Upvotes: 0

Related Questions