Exploring the power of onMounted for handling asynchronous tasks in Nuxt 3

I'm having trouble figuring out what's going on with this code snippet – the value of the repository ref doesn't seem to be updating.

Even though I used async/await, it doesn't appear to be functioning correctly. The repository is just an empty array.

I am able to access the API outside of onMounted, so I suspect there might be something amiss with it. Unfortunately, I don't have much knowledge in this area.

Take a look at the code I've written:

<template>
  <div>
    <h1>Starred Repositories</h1>
    <ul>
      <li v-for="repository in repositories" :key="repository.id">
        <h3>{{ repository.name }}</h3>
        <p>{{ repository.description }}</p>
      </li>
    </ul>
    <button @click="nextPage" :disabled="isLastPage">Next Page</button>
  </div>
</template>

<script setup>
import { Octokit } from '@octokit/core';

const repositories = ref([]);
const page = ref("1")
const runtimeConfig = useRuntimeConfig();

const octokit = new Octokit({
  auth: runtimeConfig.githubToken,
});

const nextPage = () => {
  page.value++;
}

onMounted(async () => {
  const response = await octokit.request('GET /user/starred?page=' + page.value, {
    headers: {
      'X-GitHub-Api-Version': '2022-11-28',
    },
  });
  repositories.value = response.data;
})

console.log(repositories.value);
</script>

Additionally, here's my app.vue file:

<script>
import Star from './components/Star.vue'

export default {
  components: {
    Star,
    }
}
</script>

<template>
  <Star />
</template>

Answer №1

When you check your console log, you will notice that it logs an empty array. This happens because the code is executed before the onMounted hook, which does not support async operations.

To fix this issue, move your console.log inside the onMounted hook and ensure that the endpoint actually returns data rather than an empty array.


Instead of relying on life cycle hooks for API calls, consider using the Top Level Await & Watch strategy for a better approach.

https://nuxt.com/docs/getting-started/data-fetching#watch

If you are not utilizing Nuxt's fetch helpers, you can manually handle the process as shown below:

<script setup>

import { Octokit } from '@octokit/core';

const repositories = ref([]);
const page = ref(1)
const runtimeConfig = useRuntimeConfig();

const octokit = new Octokit({
  auth: runtimeConfig.githubToken,
});

const nextPage = () => {
  page.value++;
}


const fetchStarredUsers = async (page) => {
  const response = await octokit.request(`GET /user/starred?page=${page}`, {
    headers: {
      'X-GitHub-Api-Version': '2022-11-28',
    },
  });

  if(Array.isArray(response?.data)) {
    repositories.value = response.data
    return
  }
  
  console.error('Invalid response, expected array of users').
}

// Trigger loading suspense on component entry
// https://nuxt.com/docs/getting-started/data-fetching#suspense
await fetchStarredUsers(page.value)

// Call on page change
watch(page, fetchStarredUsers)

</script>

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

Creating a mouse-resistant div with a magnet-like effect

Looking for a way to make a circle move like a magnet effect when the mouse is near, causing elements underneath it to be exposed. If you want to see an example, check out this fiddle link: http://jsfiddle.net/Cfsamet/5xFVc/1/ Here's some initial c ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

What is the best approach for iterating through the creation of Objects?

Here is a simplified version of the current code, with fewer rows and properties. var row1 = new Object(); var row2 = new Object(); var row3 = new Object(); var row4 = new Object(); var row5 = new Object(); var row6 = new Object(); var row7 = new Object() ...

How to eliminate grid lines and labels from Chart.js graphs?

Is there a way to hide the grid lines in the Radar chart using chart.js v2 for react? Desired Result, I am looking to hide the inner lines and numbers while keeping the outermost line visible. I tried to implement the following code, but it resulted in a ...

Navigating the route on express.js using two strings can be done by matching them effectively

I have a single route function that should match two different paths. The goal is to create profile pages for team members on a website, which can be accessed at www.domain.com/name. However, some team members prefer to use nicknames instead of their actua ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

Using Sequelize to Include Model Without Specifying Table Name

I am new to Sequelize I am facing an issue with "Nested Eager Loading" I have 2 tables with a one-to-many relationship Comment Table User Table This is the code I am using for the query Comment.findAll({ include: [User] }) The result I got was ...

"Encountering an issue with toUpperCase function in Next.js when incorporating slug - any

Clicking on the following link will take you to the Next.js API reference for configuring headers: https://nextjs.org/docs/api-reference/next.config.js/headers When adding the x-slug key, the code snippet looks like this: module.exports = { async heade ...

Exploring the dynamics of Django, Webpack, and Vue with the added feature of code splitting: A guide to customizing chunk

I am currently using Django in conjunction with Webpack and Vue, as well as implementing Code splitting within Webpack. The issue I am facing is that Webpack splits chunk files from the source code of .vue files, but I am unable to load these chunk files i ...

What makes Safari for Windows stand out when it comes to AJAX?

What sets Safari for Windows apart when it comes to handling AJAX requests? Moreover, are there any potential issues or challenges I should be aware of? ...

Combining arrays to create a single object: A step-by-step guide

Here is the current output I have, which contains multiple arrays: ["{"486|575":2,"484|568":4}", "{"486|575":2,"484|568":4}", "{"481|570":1,"482|564":1}"] My goal is to combine these arrays into an object with the following output using JavaScript/jQuery ...

Getting started with Babylon.js using npm: A step-by-step guide

I recently posted about my struggles with setting up Babylon.js using npm on Stack Overflow. Since I haven't received any answers yet, I was hoping to rephrase my question: Can someone provide a detailed step-by-step guide on how to set up Babylon.js ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

Moving the legend around in vue-chartJS

As someone just starting out with Vue-ChartJs, I've become quite intrigued by this: https://i.sstatic.net/j1S0z.png I'm wondering how to move the legend to the bottom of the graph. Can anyone help me with that? ...

Utilizing HTML5 canvas to extract pixel data from an image loaded from an external source

When it comes to security reasons, doing it directly may not be feasible. Nevertheless, there are rumors circulating about certain image-hosting platforms that permit the use of their images in a comparable way (could Google Picasa be one?). I might be mis ...

Valid method of confirming a user's login status

Using AJAX requests, I have implemented a user area on my website. The "Log off" button is supposed to be displayed only when the user is logged in. Here is the AJAX request for logging in a user: function requestSI() { var xhr = getXMLHttpRequest(); xhr ...

Is there a significant distinction between value and defaultValue in React JS?

React's homepage features the final illustration (A Component Using External Plugins) with a textarea: <textarea id="markdown-content" onChange={this.handleChange} defaultValue={this.state.value} /> While typing, the ...

Incorporating CSS Styles in EJS

Struggling with connecting my CSS files while using EJS. I've checked out another solution but still can't seem to get it right. Here is the code I used as a reference for my CSS file. EJS <html> <head> <meta charset="utf-8 ...

Is it possible to retrieve ALL current arrays in existence? If so, how can it be

I am working on a script and I need to fetch all existing arrays with their indexes as they are all used by the same function. Is it feasible to achieve this? The script I am working with is in shell script, but I am also curious to know if this can be do ...

Adding data to a multidimensional array in JavaScript

I am in need of creating a multidimensional JavaScript array dynamically, following this specific structure: array_answers[0][1]:"yes" array_answers[1][2]:"no" array_answers[2][2-subquestion]:"text input" array_answers[3][8]:"yes" array_answers[4] ...