Skip to content
Advertisement

TypeError: can’t access property “indexOf”, n is undefined

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:

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 is:

when it works fine I go to the page clicking 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>;

but now if I refresh, i get the above error. Rest of the code here:

fbconfig.js:

I export the db const

export const db = getFirestore()

dynamic [id] route component:

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;

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.

useEffect(() => {
let n = id;
if(n == undefined) {
  router.push('/')
} else {
const docRef = doc(db, "posts", id);

onSnapshot(docRef, (doc) => {
  console.log(doc.data())
  setPost(doc.data())
})
}

}, [])
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement