After rendering a page and retrieving data from Firebase upon clicking a button, I encounter an error upon refreshing the page:
Unhandled Runtime Error
TypeError: can't access property "indexOf", n is undefined
Source
pages\[id].js (14:19) @ Id/<
12 |
13 | useEffect(() => {
> 14 | const docRef = doc(db, "posts", id);
| ^
15 |
16 | onSnapshot(docRef, (doc) => {
17 | console.log(doc.data())
My code snippet:
I trigger the page render by clicking on this div:
<div
key={post.id}
onClick={(target) => {
userPost = post;
router.push(post.id);
}}
className='pop-out h-[150px] w-[300px] mb-5 md:mb-5 lg:mb-5 md:h-[150px] md:w-[400px] lg:h-[150px] lg:w-[400px] border-2 cursor-pointer rounded-md m-auto md:m-auto lg:m-0'
>
<h2 className='text-[30px] ml-5 mt-10 text-[gray]'>{post.title}</h2>
<div className='relative border-0 border-t-2 border-t-orange-500 w-auto top-[30px] md:top-[30px] md:h-[50px] lg:h-[50px] lg:top-[30px] text-orange-500'>
<div className='ml-2'>by {post.author}</div>
<ArrowRightIcon className='relative w-9 top-[-30px] left-[250px] md:left-[350px] lg:left-[350px] text-orange-500' />
</div>
</div>;
However, upon page refresh, I now encounter the aforementioned error. Further snippets of the code are as follows:
fbconfig.js:
The db constant is exported
export const db = getFirestore()
Dynamic component for [id] route:
const Id = () => {
const router = useRouter();
const { id } = router.query;
const [post, setPost] = useState(null);
useEffect(() => {
const docRef = doc(db, 'posts', id);
onSnapshot(docRef, (doc) => {
console.log(doc.data());
setPost(doc.data());
});
}, []);
return (
<>
<Header />
{post && (
<div className='relative text-white left-[40%] top-[100px] w-[500px] mb-10'>
<div className=''>
{post.title} · {post.author} · Link:
<a
target='_blank'
rel='noreferrer'
className='text-blue-400'
href={post.link}
>
<i> {post.link}</i>
</a>
</div>
<br />
<div
className=''
dangerouslySetInnerHTML={{ __html: post.content }}
></div>
</div>
)}
</>
);
};
export default Id;