Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use NextJS/React Class method in a Function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading