From a5e6692f6dcab2157dc92b509f61418c06b2ebd7 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Wed, 21 Sep 2022 13:50:18 +0200
Subject: fix(projects): load content dynamically and refresh table of contents

The previous way of handling content import was causing issue. So I use
dynamic import instead. However, the table of contents was not
displayed because the wrapper is first empty. I added a mutation
observer to refresh the table of contents when the body is updated.
---
 src/utils/hooks/use-mutation-observer.tsx | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
 create mode 100644 src/utils/hooks/use-mutation-observer.tsx

(limited to 'src/utils/hooks/use-mutation-observer.tsx')

diff --git a/src/utils/hooks/use-mutation-observer.tsx b/src/utils/hooks/use-mutation-observer.tsx
new file mode 100644
index 0000000..c56f7aa
--- /dev/null
+++ b/src/utils/hooks/use-mutation-observer.tsx
@@ -0,0 +1,28 @@
+import { useEffect } from 'react';
+
+type UseMutationObserverProps = {
+  callback: () => void;
+  options: MutationObserverInit;
+  nodeOrSelector: string | HTMLElement;
+};
+
+export const useMutationObserver = ({
+  callback,
+  options,
+  nodeOrSelector,
+}: UseMutationObserverProps) => {
+  useEffect(() => {
+    const targetNode =
+      typeof nodeOrSelector === 'string'
+        ? document.querySelector(nodeOrSelector)!
+        : nodeOrSelector;
+
+    const observer = new MutationObserver(callback);
+
+    observer.observe(targetNode, options);
+
+    return () => {
+      observer.disconnect();
+    };
+  }, [nodeOrSelector, options, callback]);
+};
-- 
cgit v1.2.3

