Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug (in this case it is earth but it could be jupiter or mars)

_slug.vue

<template>
  <div class="container">
    <div>
      <NuxtLogo />
      <h1 class="title">planet.title here => {{ planet.title }}</h1>
      <pre> $data here => {{ $data }}</pre>
    </div>
  </div>
</template>

<script>
import NuxtLogo from "~/components/NuxtLogo";
export default {
  components: {NuxtLogo},
  async asyncData() {
    const planet = await fetch(
      'https://api.nuxtjs.dev/planets'
    ).then((res) => res.json())
    return { planet }
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

My Web Page :

https://i.stack.imgur.com/19cy2.png

Answer №1

Here are some suggestions to enhance your code:

<template>
  <div class="container">
    <div>
      <NuxtLogo />
      <h1 class="title">planet.title will be displayed here => {{ planet.title }}</h1>
      <pre> $data will be shown here => {{ $data }}</pre>
      <section>
        <div v-for="planet in planets" :key="planet.slug">
            <p>Title of my planet: {{ planet.title }}</p>
        </div>
      </section>
    </div>
  </div>
</template>

<script>
export default {
  async asyncData() {
    const fetchCall = await fetch('https://api.nuxtjs.dev/planets')
    const planets = await fetchCall.json()
    return { planets }
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

Note: Remember to include the :key attribute.


The API response is an array. To access the title of the first planet, use planet[0].title.

You can also iterate through the entire array using v-for. For more details, visit: https://v2.vuejs.org/v2/guide/list.html#Mapping-an-Array-to-Elements-with-v-for

Answer №2

Based on the information provided, it appears that Planet is an array that requires iteration in order to display specific values. Here is a suggested code snippet:

<ul>
  <li v-for="item in planets">
    {{ item.title}}
  </li>
</ul>

Answer №3

Earth is visible in the variable $data as an array of planets.

It's advisable to change the name of the planet variable to planets, making it more descriptive of its contents.

To showcase a planet, you must retrieve it from the planets array:

<template>
  <div class="container">
    <div>
      <NuxtLogo />
      <h1 class="title">earth.title here => {{ earth.title }}</h1>
    </div>
  </div>
</template>

<script>
import NuxtLogo from "~/components/NuxtLogo";
export default {
  components: {NuxtLogo},
  async asyncData() {
    const planets = await fetch('https://api.nuxtjs.dev/planets')
        .then((res) => res.json())

    const earth = planets[0];

    return { planets, earth }
  }
}
</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

Modifying the design of a website in real-time using the EXPRESS.js and NODE.js frameworks

I successfully set up a simple website using node.js and express.js by following this helpful tutorial. My express implementation is structured like this with a jade file for the web interface. // app.js var express = require('express'), r ...

Problem encountered with displaying a component in Laravel Nova following the completion of dependency updates

Hey there, Stack Overflow community! I'm currently struggling with a rendering issue in Laravel Nova following some recent updates to dependencies within the project. Whenever I attempt to access the component in Laravel Nova, an error message pops u ...

Creating an Ajax Post request for API invocation

I'm currently setting up an Ajax Post request to interact with an API. Here is a mock curl command for reference: curl -X POST \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --h ...

"The fascinating world of asynchronous JavaScript: Promises and Del

I've been diving into Promises, but I'm a bit confused by this code snippet. Can you help clear things up for me? const promise = new Promise((resolve, reject) => { console.log('Promise started') resolve('Success') }) ...

PHP jQuery buttons for popovers

With a simple click of a button, I can generate 8 presentations and then edit each one individually by clicking on its respective name. Within this editing process, there is another form where I would like to include additional buttons that allow me to cus ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

Have you ever wondered why Vue 3 imports all JS files for every page upon the initial project load?

Is there a way to make Vue 3 import only the necessary js files for each component instead of loading all files at once when the project is first loaded? For example, if I navigate to the contact page, Vue should only import the contact.js file, rather tha ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

Calculate the overall cost from an array of information using Vue.js and Laravel

In a view, I have fields for selecting from and to dates along with branch and spare parts as dropdown options. When I select the date range, it will retrieve data including the branch name, grand total, etc. What I am trying to achieve is getting the tota ...

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

Looking for a substitute for iframes when using jQuery UI tabs?

I currently have a Spring-based web application that integrates with jQuery Tabs. What I'm doing is building a data string with specific parameters and appending it to a URL: var hrefData = "?" + item1 + "&" + item2 + "&" + item3; var href = ...

Issue with Webstorm not automatically updating changes made to JavaScript files

On my HTML page, I have included references to several JavaScript files such as: <script type="text/javascript" src="MyClass.js"></script> When debugging in WebStorm using a Python SimpleHTTPServer on Windows with Chrome, I am able to set bre ...

Issue: Error encountered while trying to use the removeAttribute() function in Selenium and Java: missing closing parenthesis after argument list

WebElement removeReadOnly=driver.findElement(By.xpath("//input[@id='mat-input-0']")); js.executeScript("document.getElementBypath('//input[@id='mat-input-0']').removeAttribute('readonly');",&quo ...

What is the best way to pass a file and a string to my C# backend using JQuery Ajax?

I have a user interface with two input fields - one for uploading a file and another for entering the file's name. I need to capture both the file (as binary data) and its corresponding name in a single AJAX request, so that I can upload the file usi ...

The save button click handler is not triggering JQuery Validation

I've been attempting for hours to get the validation working, but without success. I have added the name attribute to the input element and included script sources as well. Even after firing the validate method, the contents are still not being valida ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

uib-datepicker-popup allowing for changing minimum mode dynamically

Is there a way to dynamically set the minMode of an Angular Bootstrap Datepicker? I managed to achieve this using the following code: <input type="text" ng-model="myDate" uib-datepicker-popup="{{datepickerFormat}}" datepicker-options="{& ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

Unlocking Authorization in VueJS

Currently, I have Laravel 5.4 integrated with Vue.js 2.0. Is there a way to utilize Auth::user() within a VueJS template? Here's an example... <template> <p>{{ Auth::user()->name }}</p> </template> export default {} ...