How to create a dedicated class for all Axios requests

Viewed 29

I want to make a dedicated class where all API requests are handled so they are easier to manage, implement proper error handling & update changes.

Here is the old request method:

    const getRequest = async () => {
         try{
             const get_response = await Axios.get(`${window.ipAddress.ip}/Updates`); 
             setParentToChildData(get_response.data);
         }
         catch (err){ console.log(err)}
        setParentToChildData(data)
    }

    useEffect(() => {
        if (loadUncompleted === true) { 
             getRequest()   
        }
    }, [loadUncompleted])

Here is how I want to call it:

    useEffect(() => {
        if (loadUncompleted === true) { 
            console.log(Requests.baseGetRequest("Updates")) // checking to see if request worked
        }
    }, [loadUncompleted])

Requests.js:

import Axios from "./Axios";

export default class Requests {

    static baseGetRequest(endpoint){

        const getRequest = async (endpoint) => {
            try{
                const get_response = await Axios.get(`${window.ipAddress.ip}/${endpoint}`); 

                return get_response;
            }
            catch (err){ console.log(err)}
        }

        getRequest(endpoint)


    }

}

This will return in the console: undefined

When I check the network tab it does not run requests.

How can I fix this?

Or alternatively, if you use a specific method with this functionality, please let me know it and how to use it.

1 Answers

Changed the structure away from class, but cant use state, works though.

calling component:

    async function fetchData() {
        setParentToChildData(await baseGetRequest("Updates"));
    }

    useEffect(() => {
        if (loadUncompleted === true) { 
            fetchData();
        }
    }, [loadUncompleted])

Requests file:

export const baseGetRequest = async (endpoint) => {
    var result = ""
    var errorMsg = {};
        try {
            const get_response = await Axios.get(`${window.ipAddress.ip}/${endpoint}`);
            if (get_response.data !== null && get_response.status == 200) {
                result = get_response.data;
            }
            else {
                // handle error here
            }
        }
        catch (err) {
            if (!err?.response) { errorMsg = 'No Server Response' }
            else { errorMsg = 'Login Failed' }
        }
    return result;
}

Related