Given
import axios, { AxiosInstance } from "axios";
class ClientApi {
API_URL: string = process.env.CLIENT_API_URL;
client: AxiosInstance;
constructor() {
this.client = axios.create({
baseURL: this.API_URL,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
});
}
async doGet(url: string) {
try {
// get Authorization Headers, etc.
return await this.client.get(url,
authorizationHeaders
)
} catch (error) {
console.error(error);
}
}
}
export default ClientApi;
How do I call doGet() from a function:
import doGet from './ClientApi'
import { useEffect, useState } from "react";
export default function Users() {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
useEffect(() => {
getUserData();
}, []);
return (
<>
// render users
</>
)
async function getUserData() {
setIsLoading(true);
await doGet("/users")
.then((response) => {
setData(response.data);
});
setIsLoading(false);
}
}
There is an error in the IDE on await doGet("/users")
:
Value of type 'typeof ClientApi' is not callable
At runtime: index.js:654 Uncaught TypeError: (0 , _ClientApi__WEBPACK_IMPORTED_MODULE_1__.doPost) is not a function
2
Answers
You are importing the class. You have to instantiate it to call its methods, like:
But you don’t need a class at all, since you won’t have different instances of if. Just use a plain function like:
In your component:
The problem is that you are exporting the class and expecting to get the function directly. What you need to do is you need to instantiate the class before you use it. Hers a guide for classes
Here’s some demo code to help you understand:
This is your class:
Now for the react component:
So the class object must be created to access its member methods. Cheers 🙂