@atlaskit/editor-plugin-card
Version:
Card plugin for @atlaskit/editor-core
52 lines • 2.33 kB
JavaScript
/**
* @jsxRuntime classic
* @jsx jsx
*/
import { useEffect, useState } from 'react';
export const useFetchDatasourceInfo = ({
isRegularCardNode,
url,
cardContext,
nodeParameters
}) => {
const [datasourceId, setDatasourceId] = useState(undefined);
const [parameters, setParameters] = useState(nodeParameters);
// Since fetchData() is async, using this ready check to see if we have the parameters before passing it to the modal.
// Only non-datasource nodes will be not ready initially since we need to fetch data.
const [ready, setReady] = useState(!isRegularCardNode);
const [extensionKey, setExtensionKey] = useState(undefined);
useEffect(() => {
const fetchDatasource = async () => {
try {
var _cardContext$connecti, _cardContext$connecti2, _datasources$, _datasources$2;
if (!url || !cardContext) {
// Don't block rendering of modal of somehow we don't get these two args --> just open with empty params
setReady(true);
return;
}
const response = await (cardContext === null || cardContext === void 0 ? void 0 : (_cardContext$connecti = cardContext.connections) === null || _cardContext$connecti === void 0 ? void 0 : (_cardContext$connecti2 = _cardContext$connecti.client) === null || _cardContext$connecti2 === void 0 ? void 0 : _cardContext$connecti2.fetchData(url));
const datasources = response && response.datasources || [];
setExtensionKey(response === null || response === void 0 ? void 0 : response.meta.key);
setDatasourceId((_datasources$ = datasources[0]) === null || _datasources$ === void 0 ? void 0 : _datasources$.id);
setParameters((_datasources$2 = datasources[0]) === null || _datasources$2 === void 0 ? void 0 : _datasources$2.parameters);
setReady(true);
} catch (e) {
setDatasourceId(undefined);
setParameters(undefined);
setExtensionKey(undefined);
// If fetch somehow errors, still set ready as true so we don't block the rendering of the modal.
// It will just open with empty params.
setReady(true);
}
};
if (isRegularCardNode) {
void fetchDatasource();
}
}, [isRegularCardNode, cardContext, url]);
return {
datasourceId,
parameters,
ready,
extensionKey
};
};