vue.jsvue-router

Why am I getting a "cannot read properties of null reading ParentNode" error from vue-router?


In my Vue project I'm using vue-router. When I navigate away from a certain page I get a vague error and the router stops working. Clicking links updates the URL in the browser, but the app won't navigate to the respective pages.

The error is

TypeError: Cannot read properties of null (reading 'parentNode')

The page in question uses a watcher to update the route query parameters when the user changes filtering and sorting options. This way, when the page is refreshed/copied/bookmarked, the same options will be selected on their return.

watch(
  () => route.query,
  () => {
    selectedAddresses.value = selectedAddressesQuery.value
    selectedStatuses.value = selectedStatusesQuery.value
    selectedSortOrder.value = selectedSortOrderQuery.value
  },
  { deep: true }
)

watch(
  () => [
    selectedAddresses.value,
    selectedStatuses.value,
    selectedSortOrder.value,
  ],
  async () => {
    router.replace({
      query: {
        ...route.query,
        address: selectedAddresses.value,
        sort: selectedSortORder.value,
        status: selectedStatuses.value,
      },
    })
  }
)

Why am I getting this error when I navigate away from the page?


Solution

  • The problem was the watcher was being triggered when navigating away from the page because the query gets cleared, technically changing it.

    The solution was to add a guard statement to the watch handler to check if we're still on the current page.

    watch(
      () => route.query,
      () => {
        // prevent triggering on page leave, which clears the query
        if (route.name !== 'invoices') return
    
        selectedAddresses.value = selectedAddressesQuery.value
        selectedStatuses.value = selectedStatusesQuery.value
        selectedSortOrder.value = selectedSortOrderQuery.value
      },
      { deep: true }
    )
    

    This prevents the second watcher (that watches those values being set) from being triggered, which was trying to update the route that is no longer there.