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,31 +179,48 @@ export function useAssetURL(assetId, type, defaultSources, unknownSource) {
return; return;
} }
async function updateAssetURL() { function updateAssetURL() {
const asset = await getAsset(assetId); function increaseReferences(prevURLs) {
if (asset) { return {
setAssetURLs((prevURLs) => { ...prevURLs,
if (assetId in prevURLs) { [assetId]: {
// Check if the asset url is already added and increase references ...prevURLs[assetId],
return { references: prevURLs[assetId].references + 1,
...prevURLs, },
[assetId]: { };
...prevURLs[assetId],
references: prevURLs[assetId].references + 1,
},
};
} else {
// Create url if the asset doesn't have a url
const url = URL.createObjectURL(
new Blob([asset.file], { type: asset.mime })
);
return {
...prevURLs,
[assetId]: { url, id: assetId, references: 1 },
};
}
});
} }
function createURL(prevURLs, asset) {
const url = URL.createObjectURL(
new Blob([asset.file], { type: asset.mime })
);
return {
...prevURLs,
[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(); updateAssetURL();
@ -307,7 +324,7 @@ export function useDataURL(
if (!data) { if (!data) {
return; return;
} }
async function loadAssetId() { function loadAssetId() {
if (data.type === "default") { if (data.type === "default") {
setAssetId(data.key); setAssetId(data.key);
} else { } else {