skip to Main Content

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


  1. 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);
    }
    
    Login or Signup to reply.
  2. 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:

        class MyClass {
      age: number;
      constructor(age: number) {
        this.age = age;
      }
    
      getDoubleAge() {
        return this.age * 2;
      }
    }
    
    export default MyClass;
    

    Now for the react component:

     import MyClass from './MyClass';
        const MyComponent = () => {
          //this function instantiates MyClass and calls a method
          function myFunction(): number {
            //instance of MyClass
            const myClass = new MyClass(12);
            // call method of MyClass
            return myClass.getDoubleAge();
          }
        
          //this displays 24
          return <div>{myFunction()}</div>;
        };
        
        export default MyComponent;
    

    So the class object must be created to access its member methods. Cheers 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search