In my react application, I'm defining an Axios class with a bunch of methods, but the methods are not being recognized as functions and throwing an error. Showing is easier than explaining so... I have 3 files involved...
http-common.js has this:
import axios from 'axios';
export default axios.create({
baseURL: "http://localhost:5000/api/v1/tours",
headers: {
"Content-type": "application/json"
}
});
tours.js has this:
import http from "../http-common";
class ToursDataService {
getAll(page = 0) {
return http.get(`?page=${page}`);
}
}
export default ToursDataService
tours-list.js has this... which calls the function "getAll" in retrieveTours.
import React, { useState, useEffect } from "react";
import ToursDataService from "../services/tours";
const ToursList = props => {
const [tours, setTours] = useState([]);
useEffect(() => {
retrieveTours();
}, []);
const retrieveTours = () => {
ToursDataService.getAll()
.then(response => {
setTours(response.data.tours)
})
.catch( e => {
console.log(e);
});
}
The console claims that getAll is not a function. Why? Can anyone explain?
scheduler.development.js:173 Uncaught TypeError: _services_tours__WEBPACK_IMPORTED_MODULE_1__.default.getAll is not a function
at retrieveTours (tour-list.js:12:1)
getAll() is not a static method so you'd need to create an instance of ToursDataService...
const svc = new ToursDataService(); // create an instance
// ...
svc.getAll() // call the method on the instance
.then(...)
or make the method static
class ToursDataService {
static getAll(page = 0) {
return http.get("", { params: { page } });
}
}
Alternately, don't use classes at all since you don't appear to be encapsulating anything. You might as well just export the getAll function on its own
// tours.js
export const getAll = (page = 0) => http.get("", { params: { page } });
and
import { getAll } from "../services/tours";