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

Looping through JQuery change events

I have a challenge with handling checkboxes. Whenever a user checks one, I need to validate if they are permitted to do so. If not, I must notify them and uncheck the box. However, this process becomes recursive as it triggers the change event again! How c ...

Vue not correctly rendering dynamic styles when applied in bulk

I'm encountering an issue with applying multiple dynamic styles in Vue. Initially, the code looks like this: (The correct height is displayed) :style="minHeight ? `min-height:${getCSSUnit(minHeight,'inital')}` : ''" How ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

What is causing my fetch response to not be passed through my dispatch function?

I'm currently utilizing a node server to act as the middleman between firebase and my react native app. Could someone kindly point out what might be going awry in my fetch method below? export const fetchPostsByNewest = () => { return (dispatch ...

Organize the JSON data in a particular manner

I have a set of JSON data that looks like this: [ { "name": "Event 1", "sponsors": [ { "name": "Walmart", "location": "Seattle" }, { "name": "Target", "location": "Portland" }, { ...

``How can one validate a radio button within a reducer by utilizing the event object that is passed into the reducer process

In my React app, I am using the following reducer: const initialState = { genderRadio : false, ageRadio : false } const reducer = (state = initialState, action) => { switch(action.type) { case "VALI_RADIO_INP": console. ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

JavaScript - incorrect order for compiling

Is the user already in my SQLite database? If the user exists: return 500 (ERROR!!) If the user does not exist: return 200 (OK) This is my Node.js + Express script running on the server side. app.post('/adduser', function(req, res){ db.se ...

Activate the Bootstrap Jquery/Ajax inline editing feature by simply clicking on the Edit button

Seeking recommendations for a way to implement inline editing. When the edit button is clicked, I want the label's content to be replaced with an input text field that can be updated in my MySQL database. This is what my code looks like: <label s ...

javascript The final position achieved through requestAnimationFrame is never precise

let pf = document.querySelectorAll('.pf'); for (let i of pf) { Object.assign(i.style, { left: '400px' }) } function shiftLetters() { let start = performance.now(); let dist = -400; let dur = 500; const logoAnimate = ( ...

Exploring the attributes of optional features

Dealing with optional properties can be quite tedious. Consider the object test1 in TypeScript: interface Test { a?: { b?: { c?: { d?: string } } }; } const test1: Test = { a: { b: { c: { d: 'e' } } } }; Handling the absence of each proper ...

Grid layout showcasing masonry gallery

I've spent some time looking for a Masonry gallery with a grid layout, but couldn't find one that suited my needs. So, I decided to create my own. I implemented a customElement with grid layout, but encountered an issue when trying to assign grid ...

Can you provide me with instructions on how to create a toggle effect for a button using vanilla JavaScript?

Looking for guidance on creating a toggle effect with a button that switches between 2 images. I've managed to get it working with event listeners on btn2 and btn3, but can't seem to implement the 'toggle' effect on btn1. Any insights o ...

You should only call them after the method that returns a promise has completed

submitTCtoDB() { console.log("The selected file list contains: " + this.selectedFileList) this.readFile().then(() => { alert("ReadFile has finished, now submitting TC"); this.submitTC() }); } readFile() { return new Promise((resolve, r ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Deactivating Bootstrap Modal in Angular

Looking for advice on managing a Bootstrap Modal in Angular 7 I have a Form inside a Bootstrap Modal that I need to reset when the modal is closed (by clicking outside of it). Despite searching on Google, I haven't been able to find a solution. Any ...

JavaScript library unsuccessful in transferring data to PHP script

I am facing an issue while trying to transfer variables from javascript to a php file for execution. The problem is that the php file is not being called or executed, even though I have confirmed that it works properly when tested individually. $(function ...

TreeView Filtering

I have encountered an issue while trying to utilize a treeview filter. Below is the method I have created: var tree = [{ id: "Tree", text: "Tree", children: [ { id: "Leaf_1", text: "Leaf 1", childre ...

The Div overlay vanishes once the Javascript function is finished running

Initially, take a look at this fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/ My attempt to run JS on the fiddle has been unsuccessful, but all my code is present there, so we should be fine. I was creating my own custom image viewer, and everything was ...

Exploring ways to utilize Next.js (React) for formatting date and time with either Moment.js or alternate

When deciding on the best method for handling date formats in my next front-end app, should I use Moment.js or JavaScript functions? The data is sourced from the backend as the date type, and I want it to be displayed in a user-friendly format while consid ...