Eshaan Aggarwal
Eshaan Aggarwal

Reputation: 349

Cannot access variable before initialisation error in Vue.js project

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 class="home">
    <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

Upvotes: 2

Views: 5126

Answers (1)

kissu
kissu

Reputation: 46604

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 class="home" 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.

Upvotes: 1

Related Questions