@j2inn/app-react
Version:
React implementation of the j2inn-app framework
36 lines (35 loc) • 1.26 kB
JavaScript
/*
* Copyright (c) 2025, J2 Innovations. All Rights Reserved
*/
import { loadDynamicResource, ScriptTagType } from '@j2inn/app';
import { useEffect, useState } from 'react';
/**
* A hook for loading external resources asynchronously.
*
* @param url The url of the script or CSS file to load.
* @returns State information regarding whether the resource was loaded or failed to load.
*/
export function useDynamicResources(urls, type = ScriptTagType.javascript) {
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
useEffect(() => {
async function run() {
try {
// TODO: eventually we may want to load these resources sequentially as they
// may have resources on each other. For now we'll assume that's not the case and
// load everything concurrently for maximum performance.
await Promise.all(urls.map((url) => loadDynamicResource(url, type)));
setReady(true);
}
catch {
setReady(false);
setFailed(true);
}
}
run();
}, urls);
return {
ready,
failed,
};
}