code-edu
code-edu

Reputation: 3

Calling async method from instanced Object gives error: TypeError: Object(...) is not a function

I am currently developing an app for educational purposes and facing a problem that is probably trivial but can't get around and solve it.

So basically I am trying to fetch some data from an external API (using Axios for that). I have divided my code into modules that I am exporting to index.js file and from that, I am instancing new Object and calling my async method getResults() which in return should give me data from API. From that point a get error

TypeError: Object(...) is not a function.

Here is an example code:

Module Search.js:

export default class Search {
  constructor(query, num) {
    this.query = query;
    this.num = num;
  }

  async getResults() {
    const url = 'API_URL';
    const key = 'API_KEY';
    try {
      const res = await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
      this.result = res.data.results;
      console.log(this.result);
    } catch (error) {
      console.log(error);
    }
  }
}

And here is index.js file:

import Search from "./models/Search";
const s = new Search('cheese', 2);
s.getResults()

And finally error in console:

TypeError: Object(...) is not a function
    at Search._callee$ (Search.js:42)
    at tryCatch (runtime.js:65)
    at Generator.invoke [as _invoke] (runtime.js:303)
    at Generator.prototype.<computed> [as next] (runtime.js:117)
    at asyncGeneratorStep (Search.js:5)
    at _next (Search.js:7)
    at eval (Search.js:7)
    at new Promise (<anonymous>)
    at Search.eval (Search.js:7)
    at Search.getResults (Search.js:65)

I am probably doing something wrong here, any help and insight would be appreciated. Thanks.

Upvotes: 0

Views: 435

Answers (1)

Satyam Pathak
Satyam Pathak

Reputation: 6922

await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);

This is the line creating error,

axios is an object which you are trying to use as function

You probably wish to use get/post method provided by axios to call your endpoint

await axios.get(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);

You can have a look how you want to use axios https://github.com/axios/axios

Upvotes: 1

Related Questions