taro-hooks
Version:
为 Taro 而设计的 Hooks Library
33 lines • 1.07 kB
JavaScript
import { useRef } from '@taro-hooks/core';
import { logError, log } from '@taro-hooks/shared';
import { typeOf, isProd } from '../utils/tool';
/**
* a general generate info api hook, make direaction return, use undefined make fail
* @param {TCallback<T>} fn
* @returns {T}
*/
export function createUseInfoHook(fn, defaultReturn) {
return function () {
var safeExcute = function safeExcute() {
try {
if (!isProd) {
var _fn;
// dev mode will sync function will return a promise result
// @ts-ignore
var result = (_fn = fn()) == null ? void 0 : _fn.then == null ? void 0 : _fn.then(function (e) {
return e;
}, log);
return typeOf(result, 'Promise') && 'then' in result ? defaultReturn :
// @ts-ignore
result || fn();
}
// @ts-ignore
return fn();
} catch (e) {
logError("[createUseInfoHook]: " + e.message + ". " + String(fn));
return defaultReturn;
}
};
return useRef(safeExcute()).current;
};
}