Last active
December 10, 2025 15:49
-
-
Save sandroweb/46845204b5868f59a09d7bb9c3feefde to your computer and use it in GitHub Desktop.
Angular Directive in a React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use client"; | |
| import { useEffect, useState } from "react"; | |
| export interface ObservedElement { | |
| el: HTMLElement; | |
| value: string; | |
| } | |
| export function useAttributeObserver(attr: string) { | |
| const [elements, setElements] = useState<ObservedElement[]>([]); | |
| useEffect(() => { | |
| const updateElements = () => { | |
| const found: ObservedElement[] = []; | |
| document.querySelectorAll<HTMLElement>(`[${attr}]`).forEach((el) => { | |
| const value = el.getAttribute(attr); | |
| if (value) { | |
| found.push({ el, value }); | |
| } | |
| }); | |
| setElements(found); | |
| }; | |
| const observer = new MutationObserver(() => updateElements()); | |
| observer.observe(document.body, { | |
| attributes: true, | |
| childList: true, | |
| subtree: true, | |
| }); | |
| updateElements(); | |
| return () => observer.disconnect(); | |
| }, [attr]); | |
| return elements; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
E esse WeakSet dando bobeira aí? 🤪 Tu ia fazer um observer persistente do estado geral dos elementos?