@wordpress/block-editor
Version:
90 lines (87 loc) • 2.16 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _store = require("../../store");
var _data = require("@wordpress/data");
var _element = require("@wordpress/element");
/**
* Internal dependencies
*/
/**
* WordPress dependencies
*/
function reducer(state, action) {
switch (action.type) {
case 'RESOLVED':
return {
...state,
isFetching: false,
richData: action.richData
};
case 'ERROR':
return {
...state,
isFetching: false,
richData: null
};
case 'LOADING':
return {
...state,
isFetching: true
};
default:
throw new Error(`Unexpected action type ${action.type}`);
}
}
function useRemoteUrlData(url) {
const [state, dispatch] = (0, _element.useReducer)(reducer, {
richData: null,
isFetching: false
});
const {
fetchRichUrlData
} = (0, _data.useSelect)(select => {
const {
getSettings
} = select(_store.store);
return {
fetchRichUrlData: getSettings().__experimentalFetchRichUrlData
};
}, []);
(0, _element.useEffect)(() => {
// Only make the request if we have an actual URL
// and the fetching util is available. In some editors
// there may not be such a util.
if (url?.length && fetchRichUrlData && typeof AbortController !== 'undefined') {
dispatch({
type: 'LOADING'
});
const controller = new window.AbortController();
const signal = controller.signal;
fetchRichUrlData(url, {
signal
}).then(urlData => {
dispatch({
type: 'RESOLVED',
richData: urlData
});
}).catch(() => {
// Avoid setting state on unmounted component
if (!signal.aborted) {
dispatch({
type: 'ERROR'
});
}
});
// Cleanup: when the URL changes the abort the current request.
return () => {
controller.abort();
};
}
}, [url]);
return state;
}
var _default = exports.default = useRemoteUrlData;
//# sourceMappingURL=use-rich-url-data.js.map
;