2

I am creating react application to fetch data from youtube API and for that, I am using a method in the component but I am getting an error which says "[js] Unexpected token. A constructor, method, accessor, or property was expected." when I declare that method. Can anyone help to solve that error?

code:

class App extends Component {
  state = {
    videos: []
  };

  YTSearch({ key: API_KEY, term: "surfboards" }, function(data) {
    console.log(data);
  });


  render() {
    return (
      <div>
        <SearchBar />
      </div>
    );
  }
}

error:

enter image description here

3
  • 1
    It looks like you're trying to call the function YTSearch, with that object and function as the parameters. What was your intention? Commented Sep 13, 2018 at 22:47
  • 1
    I am trying to set up API call to youtube. **import YTSearch from "youtube-api-search"; ** Commented Sep 13, 2018 at 22:49
  • Okay the problem was that you can't call functions inside a class body like that. Commented Sep 13, 2018 at 22:57

1 Answer 1

3

My suggestion would be to put the function call in a lifecycle method:

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

  componentDidMount(){
    YTSearch({ key: API_KEY, term: "surfboards" }, function(data) {
      console.log(data);
    });
  }


  render() {
    return (
      <div>
        <SearchBar />
      </div>
    );
  }
}

read more about react lifecycle here

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.