react-native-device-info
Version:
Get device information using react-native
71 lines (60 loc) • 2.14 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useOnMount = useOnMount;
exports.useOnEvent = useOnEvent;
exports.deviceInfoEmitter = void 0;
var _react = require("react");
var _reactNative = require("react-native");
/**
* simple hook wrapper for async functions for 'on-mount / componentDidMount' that only need to fired once
* @param asyncGetter async function that 'gets' something
* @param initialResult -1 | false | 'unknown'
*/
function useOnMount(asyncGetter, initialResult) {
const [response, setResponse] = (0, _react.useState)({
loading: true,
result: initialResult
});
(0, _react.useEffect)(() => {
// async function cuz react complains if useEffect's effect param is an async function
const getAsync = async () => {
const result = await asyncGetter();
setResponse({
loading: false,
result
});
};
getAsync();
}, [asyncGetter]);
return response;
}
const deviceInfoEmitter = new _reactNative.NativeEventEmitter(_reactNative.NativeModules.RNDeviceInfo);
/**
* simple hook wrapper for handling events
* @param eventName
* @param initialValueAsyncGetter
* @param defaultValue
*/
exports.deviceInfoEmitter = deviceInfoEmitter;
function useOnEvent(eventName, initialValueAsyncGetter, defaultValue) {
const {
loading,
result: initialResult
} = useOnMount(initialValueAsyncGetter, defaultValue);
const [result, setResult] = (0, _react.useState)(defaultValue); // sets the result to what the intial value is on mount
(0, _react.useEffect)(() => {
setResult(initialResult);
}, [initialResult]); // - set up the event listener to set the result
// - set up the clean up function to remove subscription on unmount
(0, _react.useEffect)(() => {
const subscription = deviceInfoEmitter.addListener(eventName, setResult);
return () => subscription.remove();
}, [eventName]); // loading will only be true while getting the inital value. After that, it will always be false, but a new result may occur
return {
loading,
result
};
}
//# sourceMappingURL=asyncHookWrappers.js.map
;