Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card.

However, when I attempt this and inspect the Vue devtools, the image source displays as "promise".

<template>
  <div class="characters">
    <b-container>
      <b-card-group columns>
        <b-card
          v-for="character in characters"
          v-bind:key="character.id"
          :title="character.name"
          :img-src="getGiphy(character.name)"
          img-alt="Image"
          img-top
          tag="article"
          style="max-width: 20rem;"
          class="mb-2"
        >
          <b-card-text>
            This character is a {{character.role}}
          </b-card-text>
        </b-card>
      </b-card-group>
    </b-container>
  </div>
</template>

I'm attempting to retrieve the image source with

:img-src="getGiphy(character.name)"

@Component
export default class Characters extends Vue {
  public characters: Character[] = [];
  public fields: string[] = ['name', 'role'];

  public async getGiphy(name: string) {
    const giphyApi: string =
      '//api.giphy.com/v1/gifs/search?api_key=xxxxxxxxxxx&limit=1&q=';
    const response = await axios.get(giphyApi + name);
    return response.data.data[0].image_url;
  }

  private async created() {
    const response = await axios.get('/api/characters');
    this.characters = await response.data._embedded.characters;
  }

Answer №1

In Vue, promises cannot be resolved directly in properties, requiring a workaround like the following.

Example

<b-card
  ...
  :img-src="character.giphyImage"
  ...
>

TypeScript

private async created() {
  ...
  await Promise.all(this.characters.map(async character => {
    character.giphyImage = await this.getGiphy(character.name);
  }));
}

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

What is the best way to transfer variables defined in PHP to JavaScript?

Can the variables previously defined in JavaScript be used in the line that starts with $sql =? var southWestLat = map.getBounds().getSouthWest().lat(); var southWestLng = map.getBounds().getSouthWest().lng(); var northEastLat = map.getBounds().getNort ...

Tips for initializing the store in Vue when the application first starts

Seeking assistance in loading products from my pinia store upon the initial load of my Vue app. Check out my app.js below: import {createApp} from "vue"; import App from "./App.vue"; import router from "./Router/index"; impor ...

Adding an Icon to the Angular Material Snackbar in Angular 5: A Step-by-Step Guide

I recently started using Angular and have incorporated Angular Material Design for my UI elements. Within my application, I am utilizing a snackbar component. However, I am facing difficulty in adding an icon inside the snackbar despite trying various so ...

The button's status changes to disabled until I click outside the input field in Angular

I am currently facing an issue with a form (heat index calculator) that requires 2 inputs - a dropdown and a button. The button is disabled when there are no inputs or if the inputs are invalid. Everything works correctly, except for the fact that even whe ...

"Mastering the Composition API in Vue 3: A guide to defining props within the setup() method

I created a custom "loading state" mixin specifically for Vue 2: export default { props: { loading: { type: Boolean, default: false }, }, data () { return { innerLoading: false, } }, mounted () { this.innerLo ...

Access an object within the ngOnInit lifecycle hook

Is there a way to access an object from the ngOnInit function and use it outside the class in the same component? Let me explain: I am implementing an Angular Material table and want to dynamically populate it with data retrieved from Firebase. ngOnIn ...

Tips for accessing a Literal type in TypeScript instead of a Union type

I recently developed a function to generate dynamic elements. However, I encountered an issue where instead of returning the precise type of the element, it was producing a union of various <HTMLElementTagNameMap> types. function createCustomElement( ...

Problem with the property `className` not adding correctly on `$scope.eventSource`

Currently, I am utilizing the AngularJS directive to integrate the Arshaw FullCalendar. However, I am encountering an issue where the className specified in $scope.eventSource is not appearing on the event object. Here is a snippet of my code: $scope.even ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Node.JS guide on handling geonames city information

While unconventional, I wanted to share my solution since there is a lack of information on how to accomplish this task on the stack. After searching for an easy-to-use Node.JS module to process geonames data into a mongo database, I found very few project ...

Is it possible to utilize BE-provided Enum in the FE and if so, how can

How can I utilize the Enum from BE in an HTML template? Should I use it as is, or provide another one in FE? What is considered best practice? export interface UserModel { id?: number; email?: string; password?: string; gender?: UserModel ...

Display the div element only when the mouse is hovering over the button

I need a hidden text inside a div that will only appear when the mouse pointer is hovering over a specific button. Here is my current code: // Show help-text on hover $("#help-container") .mouseover(function(e) { $(this).find("#help-t ...

Tippy.js tooltips are not adapting to CSS styling as expected

My experience with tippy.js in my browser had been smooth until this morning. All of a sudden, they stopped responding to any CSS styling and simply defaulted to a dark grey background with border radius. However, they still respond to changes in the scrip ...

Angular displays incorrect HTTP error response status as 0 instead of the actual status code

In Angular, the HttpErrorResponse status is returning 0 instead of the actual status. However, the correct status is being displayed in the browser's network tab. ...

VueJS does not support certain characters in its JavaScript replace function

In my current situation, I am utilizing the replace method in the following manner: <code v-html="'/<try>/'.replace(/(?:\r\n|\r|\n)/g, 'testing')"></code> As I work with a longer string t ...

code for handling window.location.href error

Continuing from the previous question, I am facing an issue with redirecting a form to an action while using Ajax. Despite my attempts to add a redirect in the Ajax function, I keep encountering errors and getting the wrong URL. The desired redirection is ...

What is the best way to trigger an event function again once a specific condition has been satisfied?

I'm currently working on a project where I need a sidebar to scroll at a slower rate until it reaches a specific point, and then stop scrolling once that point is reached. Below is the jQuery code I've been using: $(window).on("scroll", function ...

Having trouble with Ajax not sending data to PHP in JSON format

After attempting various methods using different ajax techniques, I still cannot get this to work. Being new to ajax and json, I initially thought that the issue might be due to the data not being in a proper form. However, other ajax processes structured ...