简体   繁体   中英

Using async await for API call via custom hook

I have a custom hook sort of function as below;

export default function useApiCall() {
const fetchingData = async (url, reqData, reqType) => {
    try {
        var statObj = {         
        };
        var reqopts = {
            credentials: 'same-origin'
        }
        if (reqType === 'POST') {
            reqopts.headers = {};
            reqopts.headers['Accept'] = 'application/json';
            reqopts.headers['Content-Type'] = 'application/json;charset=utf-8';
            reqopts.method = 'POST';
            reqopts.body = JSON.stringify(reqData);
        }
        const response = await fetch(url, reqopts);
        if (!response.ok) {
            throw response;
        }
        statObj.status = "success";
        const json = await response.json();
        return [json, statObj];
    } catch (error) {
        statObj.status = "error";
        if (error && error.status) {
            switch (error.status) {
                default:
                    statObj.errorMessage = "System error occured";
                    console.error("System error occured : " + error.status);
            }
        }
        return [null, statObj];
    }

}
return fetchingData;
}

Now, I consume the function as below

const fetchFn = useApiCall();
const getData = async () => {
    const [response, statObj] = await fetchFn(url, data, 'POST');
    console.log(response);
}

So, I have the await keyword used in both the places...where I am calling and where the call is actually made.

Does the above code seem fine?

Since your custom hook is async it returns a new Promise therefore you must use the await keyword to resolve that Promise:

const myFunc = async () => {
  return 1;
}

const test2 = myFunc(); // Promise {}
const test3 = await myFunc(); // 1

There are a few things you could improve on your function:

  1. error && error.status could be error?.status (Optional Chaining);

  2. I believe you don't need the switch part since you just have the default option.

I hope it helps =]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM