3

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 Answer 1

7

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);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.