Update useAssetURL to avoid database access when not needed

This commit is contained in:
Mitchell McCaffrey 2021-05-13 16:28:02 +10:00
parent 2ac3fcf5fb
commit 2b8bc11b5c

View File

@ -179,12 +179,8 @@ export function useAssetURL(assetId, type, defaultSources, unknownSource) {
return;
}
async function updateAssetURL() {
const asset = await getAsset(assetId);
if (asset) {
setAssetURLs((prevURLs) => {
if (assetId in prevURLs) {
// Check if the asset url is already added and increase references
function updateAssetURL() {
function increaseReferences(prevURLs) {
return {
...prevURLs,
[assetId]: {
@ -192,8 +188,9 @@ export function useAssetURL(assetId, type, defaultSources, unknownSource) {
references: prevURLs[assetId].references + 1,
},
};
} else {
// Create url if the asset doesn't have a url
}
function createURL(prevURLs, asset) {
const url = URL.createObjectURL(
new Blob([asset.file], { type: asset.mime })
);
@ -202,8 +199,28 @@ export function useAssetURL(assetId, type, defaultSources, unknownSource) {
[assetId]: { url, id: assetId, references: 1 },
};
}
});
setAssetURLs((prevURLs) => {
if (assetId in prevURLs) {
// Check if the asset url is already added and increase references
return increaseReferences(prevURLs);
} else {
getAsset(assetId).then((asset) => {
if (!asset) {
return;
}
setAssetURLs((prevURLs) => {
if (assetId in prevURLs) {
// Check again if it exists
return increaseReferences(prevURLs);
} else {
// Create url if the asset doesn't have a url
return createURL(prevURLs, asset);
}
});
});
return prevURLs;
}
});
}
updateAssetURL();
@ -307,7 +324,7 @@ export function useDataURL(
if (!data) {
return;
}
async function loadAssetId() {
function loadAssetId() {
if (data.type === "default") {
setAssetId(data.key);
} else {