SolidJSS
SolidJSโ€ข5mo agoโ€ข
1 reply
Ryan

Using `querySelector*()` in a set reference function

From time to time I find the need to do something like this:
const setCalloutElementRef = (element: HTMLDivElement) => {
  const closeElements = element.querySelectorAll('[data-global-notification-close="true"]');
};

return (
  <Callout
    ref={setCalloutElementRef}
    // ...

The issue with this code is that element.querySelectorAll('[data-global-notification-close="true"]') does not return any data because the children are not available at that time. if I use queueMicrotask() like this:
const setCalloutElementRef = (element: HTMLDivElement) => {
  queueMicrotask(() => {
    const closeElements = element.querySelectorAll('[data-global-notification-close="true"]');
  });
};

return (
  <Callout
    ref={setCalloutElementRef}
    // ...

While this seems to consistently work, using any type of async code like this always gives me a little fear that it will not work all the time.

Is this is a safe way to make sure querySelector*() works or is there a better stable solution I should be done?
Was this page helpful?