Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make common API call function using fetch

I am trying to make common function which will handle all of my API calls from anywhere

I am using react": "^16.8.6" and fetch for making api call

So far what i have figure out to do is

Helper.js

export function ApiHelper(url, data = {}, method = 'POST') {
    let bearer = 'Bearer ' + localStorage.getItem('user_token');
    var promise = fetch(url, {
        method: method,
        withCredentials: true,
        // credentials: 'include',
        headers: {
            'Authorization': bearer,
            'X-FP-API-KEY': 'chaptoken', 
            'Content-Type': 'application/json'
        }
    })
    .then(res => res.json())
    .then(
        (result) => {
            console.log(result);
        },
        (error) => {
            error = error;
        }
    )
}

export function AnyOtherHelper() {
    return 'i am from helper function';
}

And here is from where i am calling this function

componentDidMount() {
    let url = `http://localhost/project/api/getdata`;
    let op = ApiHelper(url);
}

when I console result in then i am getting appropriate result but what i want to return that response how can i do this part is troubling me Even i have try to store the result in global variable and it is not working. Also i have to return the response only when promise is resolved.

like image 834
LulzAsh Avatar asked Sep 01 '26 22:09

LulzAsh


1 Answers

You are making an async call from your helper function which means, you will have to return promise from your helper function like this -

export function ApiHelper(url, data = {}, method = 'POST') {
    let bearer = 'Bearer ' + localStorage.getItem('user_token');
    return fetch(url, {  // Return promise
        method: method,
        withCredentials: true,
        // credentials: 'include',
        headers: {
            'Authorization': bearer,
            'X-FP-API-KEY': 'chaptoken',
            'Content-Type': 'application/json'
        }
    })
        .then(res => res.json())
        .then((result) => {
            console.log(result);
            return result;
        }, (error) => {
            error = error;
        })
}

USAGE

componentDidMount() {
    let url = `http://localhost/project/api/getdata`;
    ApiHelper(url)
    .then(resposnse => {
        console.log(resposnse);
    });
}
like image 127
Ashish Avatar answered Sep 04 '26 11:09

Ashish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!