diff --git a/src/app/blog/[id]/page.tsx b/src/app/blog/[id]/page.tsx index d8183d0..7d60d1c 100644 --- a/src/app/blog/[id]/page.tsx +++ b/src/app/blog/[id]/page.tsx @@ -8,38 +8,73 @@ import { BlogT2 } from '../page'; export default function Blog({ params }: { params: Promise<{ id: string }> }) { const [blog, setBlog] = useState(null); + const [error, setError] = useState(null); - useState(() => { - params.then(({id}) => { - fetch(`/api/${id}`).then((res) => { - res.json().then((data) => { - setBlog(data); - }).catch((err) => { - console.error(err); - }); + useEffect(() => { + let isMounted = true; + params + .then(({ id }) => { + return fetch(`/api/${id}`); + }) + .then((res) => { + if (!res.ok) { + throw new Error('Failed to fetch blog'); + } + return res.json(); + }) + .then((data) => { + if (isMounted) setBlog(data); + }) + .catch((err) => { + if (isMounted) setError(err.message); + console.error(err); }); - }); - }); - - if (blog !== null) { + + return () => { + isMounted = false; + }; + }, [params]); + + if (error) { return (
-

Leo's blog

-
-

{blog.title}

-

{new Date(blog.date).toLocaleString('default', { month: 'long', day: 'numeric', year: 'numeric' })}

-
{blog.markdown.replaceAll('\n-\n', '\n
\n')}
+

Leo's blog

+
+

Error loading blog: {error}

); } - else + + if (blog !== null) { return (
-

Leo's blog

-
- +

Leo's blog

+
+

{blog.title}

+

+ {new Date(blog.date).toLocaleString('default', { + month: 'long', + day: 'numeric', + year: 'numeric', + })} +

+
+ + {blog.markdown.replaceAll('\n-\n', '\n
\n')} +
+
); + } + + return ( +
+

Leo's blog

+
+ +
+
+ ); }