Composition-api: fix: Error: use getRouteBaseName function from setup root context inside computed on server side

Created on 31 Mar 2021  ·  5Comments  ·  Source: nuxt-community/composition-api

🐛 The bug
What isn't working? Describe what the bug is.

On reload (server side): When you use the getRouteBaseName function from the setup root context inside a computed, an error is render : Cannot read property 'req' of undefined

By the way: $route from setup root context is not reactive. On update, watch and computed are not triggered

🛠️ To reproduce
Steps to reproduce the behavior:

<template>
  <div>
    {{ routeBaseName }}
  </div>
</template>
<script lang="ts">
import { defineComponent, computed, useRoute } from '@nuxtjs/composition-api'

export default defineComponent({
    name: 'MyAccount',
    setup(_, { root: { getRouteBaseName } }) {
      const route = useRoute()

      const routeBaseName = computed(() => {
        return getRouteBaseName(route.value)
      })

      return {
        routeBaseName,
      }
    }
  })
</script>

🌈 Expected behaviour
No error with request parameters, there is no need :)

Informations

  • nuxt: 2.15.3
  • @nuxtjs/composition-api: ^0.22.1
  • Typescript
bug

All 5 comments

@LouisMazel Could you provide a reproduction?

Though I've not had a chance to test it, I might guess that $rootlacks some context that other Vue components have within the project. You could try something like this instead:

import { defineComponent, getCurrentInstance } from '@nuxtjs/composition-api'

export default defineComponent({
  setup() {
    const { getRouteBaseName } = getCurrentInstance().proxy
  },
})

@danielroe

Don't works: req error - Reproduction link with my own code

It's works (but TS types are missing): Reproduction link with your code proposal

Thanks your answer and your time :)

Oh my bad, I checked again the link with your proposal and it's works now (codesandbox cache issue with the fork when I tested it the first time I thinks)

So, we only have an issue when we use the getRouteBaseName function from setup context

I edited my previous comment for clarity

@LouisMazel That's likely something that can be addressed in the i18n module (which probably and understandably never foresaw access in this way). I'll have a look.

cc @rchl

I'd suggest:

import { useContext } from "@nuxtjs/composition-api";

export default defineComponent({
  setup(_) {
    const { getRouteBaseName } = useContext();
// ...

Also, you need to add nuxt-i18n to types array in tsconfig.json.

EDIT: In the end the goal is to provide a proper composition API but this should work for now, for this API at least.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tcastelly picture tcastelly  ·  7Comments

samnap11 picture samnap11  ·  6Comments

JanusSpark picture JanusSpark  ·  5Comments

Quineone picture Quineone  ·  5Comments

resessh picture resessh  ·  5Comments