Search code examples
javascriptreactjsfetch-api

Is it possible to build a generic function for the fetches?


I build an app in react.js with a lot of 'crud' operations. I am a beginner in React. For all these fetches there are always the same header (content-type, token...). And for each requests I have to resolve promises, test the code status, parse the answer, manage the errors , etc.... It is very long to write.

So I wonder if is possible to build a generic function. Something like that:

myBooks = callApi('endpoint', 'myparams');

And that's all ! The function callApi would do all the necessary (add the headers, the token, etc....).

I tried on my side, but I have not enough skills to do that in React.

Do you make your fetches with a special package ? or do you write, like me, your fetches and too bad it's long to write.

Do you have some packages to suggest?


Solution

  • I am using axios for fetching from REST APIs. You can use axios.create to create an instance that you can pass headers and the base url of your API. You could even define middlewares with axios.

    Using axios create:

    const instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });
    

    Personally, I prefer to just wrap my axios calls myself like this:

    function getHeaders() {
        return {
            accept: 'application/json',
            authorization: `Bearer ${ getStoredAuthToken() }`,
        };
    }
    
    function postHeaders() {
        return {
            'content-type': 'application/json',
            authorization: `Bearer ${ getStoredAuthToken() }`,
        };
    }
    
    export const postRequest = ( endpoint, data ) => axios
        .post( API + endpoint, data, { headers: postHeaders() } )
        .then( res => res.data )
        .catch( ( err ) => {
            LoggingUtility.error( `Error in post request to endpoint ${ endpoint }`, err );
            if ( isNetworkError( err ) ) {
                throwServerNotReachableError();
            }
            const { status } = err.response;
            if ( isUnauthorizedError( status ) ) {
                return refreshAuthToken(
                    () => postRequest( endpoint, data ),
                );
            }
            throw err;
        } );
    

    You could do something like this for every http method, e.g. deleteRequest, putRequest, postRequest etc.

    In React/Frontend land it is very common to do this in a folder called services which abstracts away all async fetches of data.