realtebo
realtebo

Reputation: 25645

React: how to define and call a function from a custom class?

My 'custom class' (not extending something other)

import Axios from "../node_modules/axios";

class ApiClient {

  getProducts(success_callback) {
    Axios.get('/api/timers')
      .then(this.checkStatus)
      .then(this.parseJSON)
      .then(success_callback)
  }

  checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
      return response;
    } else {
      const error = new Error(`HTTP Error ${response.statusText}`);
      error.status = response.statusText;
      error.response = response;
      console.log(error);
      throw error;
    }
  }

  parseJSON(response) {
    return response.json();
  }

}


export default ApiClient;

I imported in the app.js file using

import ApiClient from "./ApiClient";

And try to call it using

  componentDidMount() {
    ApiClient.getProducts( (response) => {
      this.setState({ products: response.products});
    });

  }

The error is at runtime, when browser try to call ApiClient.getProducts()

This is the error text, from Chrome:

Uncaught TypeError: _ApiClient2.default.getProducts is not a function

Please, be patient with me, I'm totally newbie with React

Upvotes: 1

Views: 110

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

getProducts is instance method., you should create instance of ApiClient and then call method

new ApiClient().getProducts()

Upvotes: 1

Related Questions