UNPKG

react-async

Version:

React component for declarative promise resolution and data fetching

63 lines (58 loc) 2.33 kB
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } import { getInitialStatus, getIdleStatus, getStatusProps, statusTypes } from "./status.js"; export const actionTypes = { start: "start", cancel: "cancel", fulfill: "fulfill", reject: "reject" }; export const init = ({ initialValue, promise, promiseFn }) => _objectSpread({ initialValue, data: initialValue instanceof Error ? undefined : initialValue, error: initialValue instanceof Error ? initialValue : undefined, value: initialValue, startedAt: promise || promiseFn ? new Date() : undefined, finishedAt: initialValue ? new Date() : undefined }, getStatusProps(getInitialStatus(initialValue, promise || promiseFn)), { counter: 0 }); export const reducer = (state, { type, payload, meta }) => { switch (type) { case actionTypes.start: return _objectSpread({}, state, { startedAt: new Date(), finishedAt: undefined }, getStatusProps(statusTypes.pending), { counter: meta.counter }); case actionTypes.cancel: return _objectSpread({}, state, { startedAt: undefined, finishedAt: undefined }, getStatusProps(getIdleStatus(state.error || state.data)), { counter: meta.counter }); case actionTypes.fulfill: return _objectSpread({}, state, { data: payload, value: payload, error: undefined, finishedAt: new Date() }, getStatusProps(statusTypes.fulfilled)); case actionTypes.reject: return _objectSpread({}, state, { error: payload, value: payload, finishedAt: new Date() }, getStatusProps(statusTypes.rejected)); } };