-
I've been trying to fix an issue that only appears in production. Currently found here Not always, but often the element with id can't be found, browser error const getElementByIdWithDimensions = (id: string) => {
const element = document.getElementById(id)
if (element === null) {
throw new Error(`Element with id '#${id}' doesn't exist.`)
}
const dimensions = element?.getBoundingClientRect();
return {
element,
dimensions,
}
} I tried a few things, including using a Async await version: const getElementByIdWithDimensions = (id: string, retries = 5, delay = 200) => {
return new Promise<{ element: HTMLElement, dimensions: DOMRect }>((resolve, reject) => {
const attempt = () => {
const element = document.getElementById(id);
if (element) {
const dimensions = element.getBoundingClientRect();
resolve({ element, dimensions });
} else if (retries > 0) {
setTimeout(() => {
retries--;
attempt();
}, delay);
} else {
reject(new Error(`The element with id '#${id}' does not exist.`));
}
};
attempt();
});
};
p5.setup = async () => {
try {
const container = await getElementByIdWithDimensions("heroContainer");
const WIDTH = container.dimensions.width;
const HEIGHT = container.dimensions.height;
p5.createCanvas(WIDTH, HEIGHT);
p5.background(BG);
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
} else {
console.error("An unexpected error occurred", error);
}
}
};
p5.windowResized = async () => {
try {
const container = await getElementByIdWithDimensions("heroContainer");
const WIDTH = container.dimensions.width;
const HEIGHT = container.dimensions.height;
p5.resizeCanvas(WIDTH, HEIGHT);
p5.background(BG);
renderTonalPalette({ p5, tone, hue, chroma, swatchDimensions });
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
} else {
console.error("An unexpected error occurred", error);
}
}
}; Again the error only happens in production, and I'm wondering how to approach it so that instead of throwing an error it reattempts after a set delay instead Sorry for all the questions, hopefully this is the last one for a little while. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
The original version should be fine, assuming hero container is always rendered and never unmounted. Did you check the server rendered DOM, the DOM changes via updates to state / props that happen and also that the id is truly always set because the sketch only runs on the client and so if the id is there, it would be found consistently. |
Beta Was this translation helpful? Give feedback.
The original version should be fine, assuming hero container is always rendered and never unmounted. Did you check the server rendered DOM, the DOM changes via updates to state / props that happen and also that the id is truly always set because the sketch only runs on the client and so if the id is there, it would be found consistently.