'Render error when using swr within react component
I am currently creating a blog and I am trying to add a viewcount to my blogposts.
import { useEffect } from 'react'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((r) => r.json())
export default function ViewCounter({
slug,
addView = false,
}: {
slug: string
addView?: boolean
}) {
console.log('ViewCounter', slug)
const { data } = useSWR(`/api/views/${slug}`, fetcher)
const viewCount = new Number(data?.total)
useEffect(() => {
console.log('ViewCounter useEffect', slug, addView)
const registerView = () =>
fetch(`/api/views/${slug}`, {
method: 'POST',
})
if (addView) {
registerView()
}
}, [slug])
// return `${viewCount > 0 ? viewCount.toLocaleString() : '–––'} views`
return (
<span className="flex items-center gap-1">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-5 w-5"
// viewBox="0 0 48 48"
// viewBox="0 0 24 24"
viewBox="0 0 1024 1024"
stroke="currentColor"
fill="currentColor"
>
<path d="M942.2 486.2C847.4 286.5 704.1 186 512 186c-192.2 0-335.4 100.5-430.2 300.3a60.3 60.3 0 0 0 0 51.5C176.6 737.5 319.9 838 512 838c192.2 0 335.4-100.5 430.2-300.3 7.7-16.2 7.7-35 0-51.5zM512 766c-161.3 0-279.4-81.8-362.7-254C232.6 339.8 350.7 258 512 258c161.3 0 279.4 81.8 362.7 254C791.5 684.2 673.4 766 512 766zm-4-430c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm0 288c-61.9 0-112-50.1-112-112s50.1-112 112-112 112 50.1 112 112-50.1 112-112 112z"></path>
</svg>
{viewCount}
</span>
)
}
When I add this component to my blog post I get the following error and I don't know why:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
When removing swr and inserting a pre defined value the component does render.
The exact error I get when I try to render the component inside a blog post
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|