Error: The property "indexOf" cannot be accessed because n is not defined

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;

Answer №1

Even though an error persisted, I decided to handle it by redirecting the user back to the homepage when 'n' is undefined to prevent future occurrences of the same error. It was the best solution I could come up with at the time.

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())
})
}

}, [])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No spaces are being retrieved from the input field

After entering "test data" in the first input box and clicking the submit button, only "test" is displayed in another input box. The goal is to have "test data" appear in the script-generated input box as well. Sample HTML Code <input name="" type="te ...

transferring information from the Quill text editor to the Node.js server

Is there a way to send data from Quilljs on the frontend to node.js on the backend? I've been searching for examples, but haven't found anything related to the backend. I tried reading the documentation for Quilljs, but I'm still struggling ...

Tailwind CSS does not support hover and group-hover functionalities

My attempt to utilize hover and group-hover in Tailwind CSS for my Next.js application has hit a snag. Despite configuring my Tailwind setup as instructed in the documentation, these classes do not seem to be working on certain pages of the application. Ev ...

Having trouble editing a form with React Hooks and Redux?

Seeking assistance with creating an edit form in React that utilizes data stored in Redux. The current form I have created is displaying the values correctly, but it appears to be read-only as no changes are being reflected when input is altered. Any advic ...

Combine words into lowercase in JavaScript variable

I'm struggling to understand why the data from a form field input is not being stored correctly in a SharePoint column data collection. Currently, when someone inputs a name into a form field, it should automatically populate a SharePoint list: http ...

Why won't the JavaScript work when linking to a carousel slide from another page?

Trying to follow this 6-year-old guide, but my JavaScript isn't triggering when the URL contains #slide_ - have things changed? Linking to a specific Bootstrap carousel slide from another page My code on page 2: <!doctype html> <html> &l ...

I am interested in generating a Stacked Chart in Google Charts using data from a JSON file

Hey there, I'm looking to generate a stacked chart using JSON data in Google Charts. My current challenge revolves around the code snippet var data = google.visualization.arrayToDataTable([. <?php $tmp = array(); require "configdashboard.php"; /* ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

Move the camera in Three.js along a path between two vectors

I created a basic scene and came across a tutorial at to help me move the camera: var timer = new Date().getTime() * 0.0005; camera.position.x = Math.floor(Math.cos( timer ) * 200); camera.position.z = Math.floor(Math.sin( timer ) * 200); However, I n ...

JavaScript: Closing a Tab

Using AngularJS for my project and I have a link that opens a tab. If the user right clicks on the link and selects open link in new tab, then on the page abc.html I have code like $window.close(); which is not working as expected. I am receiving the error ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

Material-UI rating component outputs a string instead of a numerical value

I'm encountering an issue with the Material UI rating component. Despite providing it with a number as the initial value (this.props.data.feelings_rating), it returns a string whenever I change it within my app. Below is the relevant code: Rating co ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

Crafting an interactive form

Creating a form with 2 options (Yes/No) is my current task. When the user selects one of these options, I want a collapsible subform to appear with specific details related to that selection. If the user chooses the other option, a different collapsible su ...

The compatibility between V-model and TinyMCE is unreliable

I've been working on integrating Vuejs and TinyMCE, using the @tinymce/tinymce-vue package for the Vue integration. I followed all the instructions and everything seems to be functioning properly - I can write, insert images... everything except for t ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Revert the Vue State When Navigating Back in the Browser

Background In our checkout process, we redirect to Stripe after creating an order object through an API request. To prevent users from clicking the "checkout" button multiple times during this process, we toggle a variable value to show a loading icon whe ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Determine in jQuery whether a Value is present within a JSON dataset

[ { "link" : "images/examples/image-3.png", "image" : "images/examples/image-3.png", "title" : "copy" }, { "link" : "images/examples/image-3.png", "video" : "video placeholder", "title" : "c ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...