$emit functionality within a promise

I am facing an issue with event orders in my application. I have a method for fetching data and another one to open a modal with that data, but the problem is that the modal is rendered before getting the data, resulting in the previous result briefly appearing. I understand that I need to call my methods within a promise, but I'm struggling to figure out how to do this.

App.vue

  <v-app>
    <v-main>
      <h1 class="text-center text-uppercase">Gallery</h1>
      <Cards
        :images="images"
        @addImage="updateImage($event)"
        @showModal="showPopup($event)"
      />
      <Card :image="image" v-if="modal" @closeImage="toggleImage($event)" />
    </v-main>
  </v-app>
</template>

<script>
import Cards from "./components/Cards.vue";
import Card from "./components/Card.vue";

export default {
  name: "App",

  components: { Cards, Card },

  data: () => ({
    images: {},
    image: {},
    modal: false,
  }),
  methods: {
    updateImage: function (updatedImage) {
      this.image = updatedImage;
    },
    showPopup: function (state) {
      this.modal = state;
    },
    toggleImage: function (state) {
      this.modal = state;
    },
  },
};
</script>

Cards.vue

  <v-row>
    <v-col
      v-for="image in images"
      :key="image.id"
      class="d-flex"
      cols="4"
      @click="
        getImage(image.id);
        toggleWindow();
      "
    >
      <v-img :src="image.url" :id="image.id">
        <template v-slot:placeholder>
          <v-row class="fill-height ma-0" align="center" justify="center">
            <v-progress-circular
              indeterminate
              color="grey lighten-5"
            ></v-progress-circular>
          </v-row>
        </template>
      </v-img>
    </v-col>
  </v-row>
</template>

<script>
export default {
  name: "Cards",
  props: ["images"],
  methods: {
    getImage(imageId) {
      fetch(`https://boiling-refuge-66454.herokuapp.com/images/${imageId}`)
        .then((res) => {
          if (res.status == 200) {
            return res.json();
          } else {
            throw new Error(res.status);
          }
        })
        .then((data) => {
          this.$emit("addImage", data);
        });
    },
    toggleWindow() {
      let toggle = true;
      this.$emit("showModal", toggle);
    },
  },
};
</script>

<style></style>

Answer №1

It seems that the issue lies in the asynchronous nature of getImage(). This method should return a Promise that resolves itself after the last then() block. The final then block is where

this.$emit("addImage", data);
is located.

To address this, within your @click function, you must ensure to wait for the resolution of getImage() before proceeding to call toggleWindow().

Therefore, your updated code snippet would look something like

@click="async () => { await getImage(image.id); toggleWindow();}"
.

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

Tips for retrieving the hyperlink within an HTML anchor tag using JavaScript

Here's some HTML with JavaScript: document.addEventListener('mousedown', function(event) { let elem = event.target; let jsonObject = { Key: 'mousedown', Value: event.button }; if (event.button == 2) { console ...

The status value in the result has a whitespace just before the term "success"

Apologies for the unclear question, but I encountered a strange bug in my code. I am trying to show an alert to users informing them that the updates have been successfully completed. Below is the code snippet containing an if() block where the alert shoul ...

Incorporating a GLTF Model in a Basic React Three Fiber Environment

I am attempting to incorporate a model with diffuse and bump textures into a basic scene using react 3 fiber. Despite my best efforts, I can't seem to figure out what mistake I might be making. You can view the sandbox here: https://codesandbox.io/s ...

The Role of AI in Gaming

I am currently developing a car racing game using THREE.js. I am inquiring about how to incorporate Artificial Intelligence into the enemy cars so that they can actively search for and target the player. Can you provide insight into the algorithms typica ...

What is the best way to test a React component that includes a Router, Redux, and two Higher Order Components using Jest and Enzyme?

I'm currently facing a challenge with this issue. I have a React Component that is linked to React Router 4 and Redux store, and it's wrapped by two HOCs. It may sound complicated, but that's how it was implemented. Here's the export st ...

Verifying the status following a promise execution in the initial promise function

Below is the function I am currently working with: startGame = () => { this.buildDeck() .then(this.shuffleDeck) .then(this.dealToPlayer) .then(setTimeout(this.dealToPlayer, 2000)) .then(setTimeout(this.dealToDealer, 4000)) } In ...

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

A specific string exemption for HTML even numbers

Within this HTML code, I have specified that the even-numbered rows should have a different format. However, if the string "QACheck:" appears in a row, I want to use the odd-numbered row format. Even if it occurs in an even-numbered row. Can someone assis ...

JavaScript / AngularJS - Efficient Boolean Switching

My group of Boolean variables can toggle other variables to false when set to true. I am looking for a clean pattern for this approach, especially since the number of boolean variables may increase. angular.module("app", []) .controller("controller", ...

Chat lines in Chrome displaying double entries - troubleshooting needed

I developed a chat plugin for my website with a simple HTML structure: <div id="div_chat"> <ul id="ul_chat"> </ul> </div> <div id="div_inputchatline"> <input type="text" id="input_chatline" name="input_chatline" val ...

Finding the identifier of an element within a <select> tag in React

I am looking to get the id of a selected option in my handleSubmit(event) function. The code snippet below shows a select element with various options: <select id="category"> <option id="1">Travel</option> <option id="2">Au ...

Utilizing ECMA 5 code within Internet Explorer 8

My current code includes the use of hls.js for playing hls streams. The original code is in ECMA version 6 and then transpiled into ECMA 5, which can be found in the dist folder (link provided). It works fine in most cases. However, when trying to render ...

Issue with updating Leaflet map within Bootstrap 4 tabs

Here is an issue I am facing in my project. I am currently working on a Bootstrap 4 page that has multiple tabs. Each tab contains a leaflet map, dygraphs, and other content. The problem arises when I switch between tabs, the map does not reload properly ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

What are the steps to design a 3D website similar to this one? (Using babylon.js or KRpano?)

I stumbled upon this awesome site https://greenewera.com.tw/2023/ and I'm intrigued by its design and functionality. After using wappalyzer, I discovered that it is built using Vue.js and running on Ngins as the web server. But I'm particularly ...

Encrypting data using NodeJS Crypto and decrypting it in front-end JavaScript

I'm currently on the hunt for a way to perform AES256 CBC decryption on the client side. When working with nodeJS, I typically utilize this function for encryption: exports.encrypt = function(txt, cryptkey){ var cipher = crypto.createCipher(' ...

Displaying Modal from a separate component

CardComponent: export class Card extends Component<Prop, State> { state = { isCancelModalOpen: false, }; marketService = new MarketService(); deleteMarket = () => { this.marketService .deleteMar( ...

Installation of the package was unsuccessful: npm encountered an error with code ERESOLVE, indicating that it was unable to destructure the property 'name' from 'node' as it is currently null

Mohameds-MacBook-Air:client sakeeljawfer$ ng add @ng-bootstrap/ng-bootstrap ℹ Using package manager: npm ✔ Found compatible package version: @ng-bootstrap/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a ...

Obtaining a string from the String prototype can be achieved by using

My goal is to create a custom log method for the String object that will print out the actual string value, but I'm facing some difficulties in getting it to work correctly. String.prototype.log = function() { console.log(this.valueOf()); } &apos ...

Can ng-packagr create scripts that are compatible with running in a web browser like regular JavaScript?

Is it feasible to utilize ng-packagr to compile a library into a single script file that can be executed on a web browser by importing it as <script src="bundle.js"></script>? For instance, if I have a main.ts file that contains cons ...