Reputation: 21
After adding an SWR data fetch to my react component it crashes, if I comment it out it works fine.
I get the following error after uncommenting line const { data } = useSWR(`/api/views/${slug}`, fetcher)
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.
The component
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
}) {
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">
{data && data?.total}
</span>
)
}
Maybe it also has something to do with the fact that this component is included within another component that uses getStaticPaths and getStaticProps?
The full codebase can be found here: https://github.com/SennR-1952135/sennr
Upvotes: 0
Views: 480
Reputation: 21
The problem seemed to be with the version of swr, i had to use 1.1.2 or lower, still dont know the exact reason but it works.
Upvotes: 1