@sanity/preview-kit
Version:
General purpose utils for live content and visual editing
55 lines (54 loc) • 2.32 kB
JavaScript
"use client";
;
var react = require("react"), hooks = require("../_chunks-cjs/hooks.cjs");
function useLiveQuery(initialData, query, queryParams2) {
const defineStore = react.useContext(hooks.defineStoreContext), queryParams = hooks.useQueryParams(queryParams2), store = react.useMemo(
() => defineStore?.(initialData, query, queryParams),
[defineStore, initialData, queryParams, query]
), [serverSnapshot] = react.useState(() => {
if (initialData === void 0)
throw new Error(
"initialSnapshot can't be undefined, if you don't want an initial value use null instead"
);
try {
return JSON.parse(JSON.stringify(initialData));
} catch (error) {
return console.warn(
"Failed to deep clone initialSnapshot, this is likely an error and an indication that the snapshot isn't JSON serializable",
{ initialSnapshot: initialData, error }
), initialData;
}
}), getServerSnapshot = react.useCallback(() => serverSnapshot, [serverSnapshot]);
return [
react.useSyncExternalStore(
store?.subscribe || noop,
store?.getSnapshot || getServerSnapshot,
getServerSnapshot
),
defineStore !== null
];
}
function noop() {
return () => {
};
}
function LiveQueryClientComponent(props) {
const { initialData, query, params, children, throwOnMissingProvider = !0 } = props, [data, enabled] = useLiveQuery(initialData, query, params);
if (throwOnMissingProvider && !enabled)
throw new Error(
"<LiveQuery> require you to wrap them in a parent <LiveQueryProvider> when its 'enabled' prop is true, or set the 'throwOnMissingProvider' prop to 'false' to ignore this error"
);
return react.isValidElement(children) ? react.cloneElement(children, {
// eslint-disable-next-line no-warning-comments
// @ts-expect-error -- @todo fix the typings
...children.props,
// all child props should override, except for `data`
data,
// eslint-disable-next-line no-warning-comments
// @ts-expect-error -- @todo fix the typings
ref: children.ref
}) : react.Children.count(children) > 1 ? react.Children.only(null) : null;
}
LiveQueryClientComponent.displayName = "LiveQueryClientComponent";
module.exports = LiveQueryClientComponent;
//# sourceMappingURL=client-component.cjs.map