@ledgerhq/live-common
Version:
Common ground for the Ledger Live apps
44 lines • 2.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useUpdateFirmware = useUpdateFirmware;
const react_1 = require("react");
const updateFirmware_1 = require("../actions/updateFirmware");
const operators_1 = require("rxjs/operators");
const STATE_UPDATE_THROTTLE = 500;
/**
* Hook used to trigger the update of a firmware, it isn't triggered right away but rather returns
* a function that triggers it. The function can be called multiple times in order to implement a
* retry strategy
* @param Args Object containing the arguments of the hook: a deviceId and an optional device action to used (useful for mocking)
* @returns An object containing the current state of the update and the trigger update function
*/
function useUpdateFirmware({ deviceId, deviceName, updateFirmwareAction = updateFirmware_1.updateFirmwareAction, }) {
const [updateState, setUpdateState] = (0, react_1.useState)(updateFirmware_1.initialState);
const [nonce, setNonce] = (0, react_1.useState)(0);
(0, react_1.useEffect)(() => {
if (nonce > 0) {
const sub = updateFirmwareAction({
deviceId,
deviceName,
})
.pipe(
// in order to correctly throttle the events without losing any important events
// we need to buffer them according to the throttle time and always return the latest event from the buffer
(0, operators_1.bufferTime)(STATE_UPDATE_THROTTLE), (0, operators_1.map)(events => events[events.length - 1]), (0, operators_1.filter)(e => e !== undefined))
.subscribe({
next: (state) => {
setUpdateState(state);
},
});
return () => {
sub.unsubscribe();
};
}
}, [deviceId, updateFirmwareAction, nonce, deviceName]);
const triggerUpdate = (0, react_1.useCallback)(() => {
setUpdateState(updateFirmware_1.initialState);
setNonce(nonce => nonce + 1);
}, []);
return { updateState, triggerUpdate };
}
//# sourceMappingURL=useUpdateFirmware.js.map