Home > Net >  Cannot access variable before initialisation error in Vue.js project
Cannot access variable before initialisation error in Vue.js project

Time:10-16

I am currently working on a Twitter clone, using Vue 3. The source code for the same can be found here.

The code for the HomeView.vue is as follows:

<template>
  <div >
    <Tweet 
      v-for="tweet in tweets" 
      :key="tweet._id" 
      :tweet="tweet" />
  </div>
</template>

<script>
import { ref } from 'vue';
import Tweet from '../components/Tweet';
import tweets from '../tweets';

export default {
  setup () {
    const tweets = ref(tweets);

    return {
      tweets,
      Tweet
    }
  }
}
</script>

But upon executing the same I get the following error in the developer's console.

Uncaught (in promise) ReferenceError: Cannot access 'tweets' before initialization

Can anyone help me in figuring out why is this happening?

CodePudding user response:

Not a Composition API expert but I guess that looking at the lifecycle, you can't use tweets straight like that because they are not directly available. They are populated afterwards.

While your template is sync, hence it is erroring because it cannot access something when it's (initially) undefined.

Making a <div v-if="tweets"> may be a solution, otherwise maybe a combo with watch and Suspense, not sure.

PS: also you have 2 tweets variables here, this may cause some bugs be careful.

  • Related