I want to get a doc from firebase on page render, which I do get first(following a button), but after I refresh the page I get this error:
JavaScript
x
15
15
1
Unhandled Runtime Error
2
3
TypeError: can't access property "indexOf", n is undefined
4
Source
5
6
pages[id].js (14:19) @ Id/<
7
8
12 |
9
13 | useEffect(() => {
10
> 14 | const docRef = doc(db, "posts", id);
11
| ^
12
15 |
13
16 | onSnapshot(docRef, (doc) => {
14
17 | console.log(doc.data())
15
My code is:
when it works fine I go to the page clicking this div:
JavaScript
1
15
15
1
<div
2
key={post.id}
3
onClick={(target) => {
4
userPost = post;
5
router.push(post.id);
6
}}
7
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'
8
>
9
<h2 className='text-[30px] ml-5 mt-10 text-[gray]'>{post.title}</h2>
10
<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'>
11
<div className='ml-2'>by {post.author}</div>
12
<ArrowRightIcon className='relative w-9 top-[-30px] left-[250px] md:left-[350px] lg:left-[350px] text-orange-500' />
13
</div>
14
</div>;
15
but now if I refresh, i get the above error. Rest of the code here:
fbconfig.js:
I export the db const
JavaScript
1
2
1
export const db = getFirestore()
2
dynamic [id] route component:
JavaScript
1
42
42
1
const Id = () => {
2
const router = useRouter();
3
const { id } = router.query;
4
const [post, setPost] = useState(null);
5
6
useEffect(() => {
7
const docRef = doc(db, 'posts', id);
8
9
onSnapshot(docRef, (doc) => {
10
console.log(doc.data());
11
setPost(doc.data());
12
});
13
}, []);
14
15
return (
16
<>
17
<Header />
18
{post && (
19
<div className='relative text-white left-[40%] top-[100px] w-[500px] mb-10'>
20
<div className=''>
21
{post.title} · {post.author} · Link:
22
<a
23
target='_blank'
24
rel='noreferrer'
25
className='text-blue-400'
26
href={post.link}
27
>
28
<i> {post.link}</i>
29
</a>
30
</div>
31
<br />
32
<div
33
className=''
34
dangerouslySetInnerHTML={{ __html: post.content }}
35
></div>
36
</div>
37
)}
38
</>
39
);
40
};
41
export default Id;
42
Advertisement
Answer
It still gave me an error, but I just redirected the user back to the homepage if n is undefined so it won’t give me this error again. I had no better idea than this.
JavaScript
1
15
15
1
useEffect(() => {
2
let n = id;
3
if(n == undefined) {
4
router.push('/')
5
} else {
6
const docRef = doc(db, "posts", id);
7
8
onSnapshot(docRef, (doc) => {
9
console.log(doc.data())
10
setPost(doc.data())
11
})
12
}
13
14
}, [])
15