import { shell } from './shell' import { ACTIONS } from './core' /** * Function to warn the admin-shell to start the global * loadbar animation. * IMPORTANT: If using the admin-shell v4, make sure you * call this function only once, because the admin-shell v4 * has a different global loader, that is intended to work * in a linear way. This must be used along with the `stopLoading` * function. * * @returns true * * # @examples * * ## In the case of a __single query page__ * ```jsx * // other necessary imports up here... * import { startLoading, stopLoading } from `admin-shell-utils` * * const App = () => { * const { data, loading } = useQuery(SomeQueryDocument, { * onCompleted: () => stopLoading(), * onError: () => stopLoading() * }) * * if (loading) { * startLoading() * * return ( * Loading... * ) * } * * return ( * My app * ) * } * ``` * * ## In the case of a __multiple queries page__ * ```jsx * // other necessary imports up here... * import { startLoading, stopLoading } from `admin-shell-utils` * * const App = () => { * const { data, loading } = useQuery(SomeQueryDocument) * const { data: otherData, loading: otherLoading } = useQuery(SomeOtherQueryDocument) * const startedLoading = useRef(false) * * useEffect(() => { * if ((loading || otherLoading) && !startedLoading.current) { * startedLoading.current = startLoading() * } * * if (!loading && !otherLoading) { * stopLoading() * } * }, [loading, otherLoading, startedLoading]) * * return ( * My app * ) * } * ``` * */ export function startLoading() { shell.postMessage(ACTIONS.START_LOADING(), '*') return true } /** * Function to warn the admin-shell to stop the global * loadbar animation. * IMPORTANT: This must be used along with the `startLoading` * function. * * @returns true * * # @examples * * ## In the case of a __single query page__ * ```jsx * // other necessary imports up here... * import { startLoading, stopLoading } from `admin-shell-utils` * * const App = () => { * const { data, loading } = useQuery(SomeQueryDocument, { * onCompleted: () => stopLoading(), * onError: () => stopLoading() * }) * * if (loading) { * startLoading() * * return ( * Loading... * ) * } * * return ( * My app * ) * } * ``` * * ## In the case of a __multiple queries page__ * ```jsx * // other necessary imports up here... * import { startLoading, stopLoading } from `admin-shell-utils` * * const App = () => { * const { data, loading } = useQuery(SomeQueryDocument) * const { data: otherData, loading: otherLoading } = useQuery(SomeOtherQueryDocument) * const startedLoading = useRef(false) * * useEffect(() => { * if ((loading || otherLoading) && !startedLoading.current) { * startedLoading.current = startLoading() * } * * if (!loading && !otherLoading) { * stopLoading() * } * }, [loading, otherLoading, startedLoading]) * * return ( * My app * ) * } * ``` * */ export function stopLoading() { shell.postMessage(ACTIONS.STOP_LOADING(), '*') return true }