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
>Solution :
You are importing the class. You have to instantiate it to call its methods, like:
import ClientApi from './ClientApi'
const client = new ClientApi();
...
function getUserData() {
setIsLoading(true);
client.doGet("/users")
.then((response) => {
setData(response.data);
});
setIsLoading(false);
}
But you don’t need a class at all, since you won’t have different instances of if. Just use a plain function like:
import { AxiosInstance } from "axios";
const API_URL = process.env.CLIENT_API_URL;
const client = axios.create({
baseURL: API_URL,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
});
export async function doGet(url: string) {
// get Authorization Headers, etc.
return await client.get(url, authorizationHeaders);
}
In your component:
import { doGet } from './api';
...
function getUserData() {
setIsLoading(true);
doGet("/users")
.then((response) => {
setData(response.data);
});
setIsLoading(false);
}