How to make common API call function using fetch

狂风中的少年 提交于 2019-12-24 00:30:04

问题


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.


回答1:


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);
    });
}


来源:https://stackoverflow.com/questions/56912931/how-to-make-common-api-call-function-using-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!