Tips on loading and rendering images using a specified URL property in Nuxt

Recently diving into Nuxt (and also Vuejs) in SPA mode, I've run into an issue with image loading. The image doesn't load until I type something in the search input field. Below are the relevant snippets of my code:

<template>
<input 
    class="search" 
    type="text" 
    placeholder="search name" 
    v-model="searchTerm" 
    @keyup.enter="filterPokemonList">
<button @click="clearSearchTerm">clear</button>
<div class="container">
    <div class="card" v-for="(pokemon, index) in pokemonList" :key="index" >{{pokemon.name}}
      <!-- Here begins my problem of image loading -->
      <div v-if="pokemon&&pokemon.sprites">
         <img :src="pokemon.sprites.front_default" alt="sprite" width="96px" height="96px">
      </div>
      <div v-if="!pokemon.sprites">
         <img src="~/assets/images/loading.png" alt="loading" width="96px" height="60px">
      </div>
      <!-- End -->
      <nuxt-link :to="'/'+pokemon.name">
        <b-button class="card-btn" size="sm" variant="outline-dark">detail</b-button>
      </nuxt-link>
      <b-button class="card-btn" size="sm" variant="outline-dark" @click="addToEquipe(pokemon)">add</b-button>
    </div>
</div>
</template>

In my page script:

<script>
import axios from 'axios'

const PATH_BASE = 'https://pokeapi.co/api/v2/'
const POKEMON = 'pokemon'
const LIMIT = 'limit='


const getPokemonData$ = url => {
  return axios.get(url)
}
export const getPokemon$ = (name) =>
  axios.get(`${PATH_BASE+POKEMON}/${name}`).then(res => res.data)

export const getPokemons$ = (listNumber) => 
  axios.get(`${PATH_BASE+POKEMON}?${LIMIT+listNumber}`).then(
    res => {
      let pkList = res.data.results
      pkList.map((pk) =>
        getPokemonData$(pk.url).then(res =>
          pk.sprites = res.data.sprites
        )
      )
      return pkList
    } 
  )
export default {
data() {
    return {
      entirePokemonsCache: [],
      pokemonList: [],
      searchTerm: "",
    }
},
async asyncData (context) {
    const result = await getPokemons$(100)
    return { pokemonList: result }
},
</script>

It's clear that when fetching data via HTTP GET, I then perform another related HTTP GET to populate additional properties. How can I ensure images load initially without needing user interaction?

Answer №1

Instead of fetching all the Pokemons from https://pokeapi.co/api/v2/pokemon and then looping through them using a map or for loop, I opted for a different approach. I decided to individually retrieve each Pokemon by calling https://pokeapi.co/api/v2/pokemon/id.

axios.get('https://pokeapi.co/api/v2/**pokemon**').then(
    res => {
        let pkList = res.data.results
        pkList.map((pk) =>
            axios.get(pk.url).then(res =>
            pk.sprites = res.data.sprites
            ....

If you have an alternative solution, feel free to share it with me :)

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

Adjust the badge's color based on the status retrieved from the jQuery AJAX call

I've been working on retrieving data from an endpoint through a get request, and I'm looking to adjust the color of the request status based on the response. $.ajax({ type: 'GET', url: 'api/v1/service/tax', succe ...

Clicking on a DIV using jQuery, with anchor elements

I have a method for creating clickable divs that works well for me: <div class="clickable" url="http://google.com"> blah blah </div> Afterwards, I use the following jQuery code: $("div.clickable").click( function() { window.location ...

Traverse the JSON array in a loop

I am currently facing an issue with looping through a JSON array that I am passing to PHP. At this point, I am only passing one array and receiving the same array back from the PHP file. While I can loop through the data in JavaScript, I am encountering er ...

How can we handle multiple asynchronous calls within a function?

In the process of developing a dynamic page with heavy AJAX interactions that update values in selectors based on prior selections. Currently, working on implementing a "repopulate" feature to fill in selectors based on previous entries. Whenever Selector ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...

Every time an input is altered, the onClick function is invoked

I am facing an issue while trying to send data to a local server using an onclick function. Every time the input field is changed, the function gets called unnecessarily and I can't seem to figure out why this is happening. const sendDataToServer = () ...

Menu options submerged beneath the surface of a concealed container with overflow property

Attempting to enhance the ui-grid by adding more options to each row using the "3 dots" approach. However, encountered an issue where the dropdown menu extends beyond the screen due to the use of position: absolute. Unable to switch to position: relative b ...

Is there a way to properly direct to an internal page while utilizing [routerLink] and setting target="_blank" without triggering a full page reload?

I'm attempting to use [routerLink] along with target="_blank" to direct to an internal page without triggering a full app reload. Currently, the page opens in a new tab, but the whole application is refreshed. Here is the HTML: <a [routerLink]=" ...

Having trouble with JQuery's append method on the <head> tag?

I am having an issue with this particular code block. It seems to be unable to insert the meta tag into the head section. Any suggestions on how to resolve this problem? <html> <head> <title>hello world</title> </head> < ...

Does the global $.ajaxSetup() function not impact $.ajax() calls within distinct functions?

Is it possible to make the effects of $.ajaxSetup() reach into function bodies? I'm having trouble getting $.ajaxSetup() to impact the $.ajax() calls within functions. Here is an example: In the code snippet below, the ajax request made by function f ...

Tips for concentrating on the initial input field produced by an ng-repeat in AngularJS

Currently, I am dynamically generating input fields using ng-repeat and everything is working smoothly. However, my requirement is to set focus on the first input that is generated by this ng-repeat based on their sequenceId values. So far, I have attempte ...

A creative way to display a div upon hovering over a link dynamically

My website has dynamically generated a tags, each with its own corresponding div containing unique content and height. I want to make it so that when a user hovers over an a tag, the matching div is displayed. The div should appear at the position of the m ...

Achieving www prefix enforcement for loading js file

I am facing an issue with the script on my website, which is built using OpenCart. The problem arises when accessing the site with a www prefix - the JavaScript file fails to load. However, when accessed without the www prefix (e.g. example.com), everyth ...

Creating a dynamic PHP calculator that provides instant results by taking input from an HTML form

For the sheer joy of coding in PHP, I decided to create a calculator. Take a look at the result: PHPTest Apologies for some German text within. Here's the Code: <?php $umsatz = $_POST['umsatz']; $varkost = $_POST['varkost& ...

The onLoad event of the <picture /> element is not consistently being triggered

I'm encountering an issue where the onLoad event on the picture element is not consistently firing. I have tried adding the onload event listener to both the picture and image elements, but sometimes they both fire and other times neither of them do. ...

Guide to loading JQuery in an electron webview using a proxy

Currently, I am configuring an electron application with an index.html file that includes a webview. The webview has a reverse proxy connected to it which modifies all "/" routes. Due to this setup, I am unable to load CDN libraries such as JQUERY within t ...

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

Tips for updating a field using Jquery

For my PHP + MYSQL + JQuery editing form, I am wondering how to display the updated data in the fields without refreshing the entire page after saving it to the database. Currently, I have this code snippet: $(document).ready(function (e) { $('f ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Output the JSON string retrieved from a specified URL

I'm currently working on using ajax to retrieve and parse JSON data from a specific URL. I am looking for assistance on how to store the parsed array into a variable. Any guidance or suggestions would be greatly appreciated. Thank you! function rvOff ...