Is there a way to trigger another API call when clicking a button in Vue.js?

I recently started using vue js and I am facing a challenge with this component. I am attempting to trigger another API call when one of the list options is clicked.

<template>
  <div>
    <h1 class="text-center text-4xl font-bold">Our Product</h1>
    <ul class="flex items-center justify-center gap-5">
      <li class="cursor-pointer text-xl" @click="handleClick(1)">Clothes</li>
      <li class="cursor-pointer text-xl" @click="handleClick(5)">Shoes</li>
      <li class="cursor-pointer text-xl" @click="handleClick(2)">Watches</li>
      <li class="cursor-pointer text-xl" @click="handleClick(4)">Furniture</li>
    </ul>
    <div class="grid grid-cols-3 gap-5">
      <div v-for="store in stores" :key="store.category.id">
        <div class="max-w-xl h-auto">
          <img :src="store.images[0]" alt="img" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, ref, watch } from "vue";

import Clothes from "../Products/Clothes.vue";
import Shoes from "../Products/Shoes.vue";
import axios from "axios";

export default {
  components: {
    Clothes,
    Shoes,
  },
  props: [],
  data() {
    return {
      stores: [],
      errors: [],
      product: ref(1), //Changing value for product
    };
  },
  methods: {
    handleClick(params) {
      this.product = params;
      console.log(this.product);
    },
  },

//Triggering the API call
  async created() {
    await axios
      .get(
        `https://api.escuelajs.co/api/v1/categories/${this.product}/products`
      )
      .then((res) => {
        this.stores = res.data;
        console.log(this.stores);
      })
      .catch((e) => {
        console.log(this.errors.push(e));
      });
  },
I hope that by clicking on a specific product, it will change to the designated number. Thank you!

Answer №1

  1. Avoid using ref when working with the option api, as it can lead to confusion between option and composition api (specifically the setup function)

  2. Consider moving your API call to a separate method that can be called from both the created lifecycle hook and the handleClick method

export default {
  components: {
    Clothes,
    Shoes,
  },
  data() {
    return {
      product: 1,
      stores: [],
      errors: [],
    };
  },
  methods: {
    fetchProduct(productId) {
      return axios.get(`https://api.escuelajs.co/api/v1/categories/${productId}/products`)
        .then((res) => {
          this.stores = res.data;
        })
        .catch((e) => {
          this.errors.push(e);
          console.error(e);
        });
    },
    handleClick(productId) {
      this.product = productId;
      this.fetchProduct(productId);
    },
  },

  //API call is made in the created lifecycle hook
  async created() {
    await this.fetchProduct(this.product);
  },
};

Answer №2

Make sure to be patient for the sync call:

const application = Vue.createApp({
  data() {
    return {
      product: 1,
      stores: [],
      errors: [],
    };
  },
  methods: {
    async fetchProduct(productId) {
      await axios.get(`https://api.escuelajs.co/api/v1/categories/${productId}/products`)
        .then((res) => {
          this.stores = res.data;
        })
        .catch((e) => {
          this.errors.push(e);
          console.error(e);
        });
    },
    handleClick(productId) {
      this.product = productId;
      this.fetchProduct(productId);
    },
  },
  async created() {
    await this.fetchProduct(this.product);
  },
})
application.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/axios.min.js" integrity="sha512-QTnb9BQkG4fBYIt9JGvYmxPpd6TBeKp6lsUrtiVQsrJ9sb33Bn9s0wMQO9qVBFbPX3xHRAsBHvXlcsrnJjExjg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
  <button @click="handleClick(3)">get productid 3</button>
  {{stores}}
</div>

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

React Redux components are failing to render after changes are made to the state array

I'm fairly new to using React, Redux, and Thunk in my project. Right now, I'm facing an issue where I fetch an array from an API call in my action/reducer, but it doesn't re-render in the connected component/container that's hooked up t ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

Utilizing Vuetify's V-File-input component along with an append-outer-icon functionality

Looking to customize the v-file-input icon and its placement? I tried using the "append-outer-icon" attribute to achieve this, but unfortunately clicking on the icon doesn't trigger any action. Ideally, I would like to click on the "append-outer-icon" ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

The conceal feature doesn't appear to be functioning properly on jQuery Mobile

I am facing an issue with a small mobile app built using jQuery Mobile. Within a div, I have three buttons and other content. My goal is to hide these three buttons if the user's device is running on Windows (WP). The buttons are defined as follows: ...

The IsArray() function in IE8 encounters an issue where it expects an error object

I am interested to know why IE8 is having trouble with this line of code: if (isArray(obj)) When I check in the IE8 javascript console, I see the following: >>obj {...} >>typeof(obj) "object" >>Object.prototype.toString.call(obj) "[obj ...

Issue encountered when attempting to retrieve elements within an HTA's IFrame

We are currently working on automating an Intranet site using HTA and JavaScript. To bypass the browser security settings, we have implemented an Iframe within the HTA itself instead of opening the site in a browser. Despite being able to successfully logi ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Oops! Looks like there was an error: $http is not defined

I'm facing a challenge with implementing $http in the AngularJS framework. I've gone through various other resources on this issue, but I can't seem to figure out what I'm doing incorrectly. Any assistance would be highly appreciated. T ...

Accessing the current frame of a video in JavaScript or jQuery

Currently, I am experimenting with the HTML video tag to play a video. Instead of retrieving the "currentTime" of the video, I am interested in obtaining the current frame using either jQuery or JavaScript. Despite my efforts in calculating the frame rate ...

When the clearInterval function is invoked - either when the timer is modified or when the rendering is detached from the setInterval it is linked to

As a new React developer, I've come across a problem that has me stuck. Does the setInterval associated with a specific render get cleared automatically? import React, { useState, useEffect, useRef } from "react"; import ReactDOM from ...

Transferring previously obtained data to templateProvider within AngularJS

I'm currently working with AngularJS 1.3 and UI-Router. I have a state set up with a resolve and a templateProvider. My goal is to utilize the data fetched from the database in the resolve within the templateProvider without having to make duplicate ...

Android Webview onLoad function provides incorrect height information

When I load a file:// URL into the webview, issues with height calculation arise. Instead of using WRAP_CONTENT, I calculate the height in javascript during the onPageFinished event in Android. However, about 2 out of 5 times, the javascript reports an inc ...

Struggling with the loading of intricate attribute data into an array of arrays

I am struggling with loading different data attributes into an array of arrays. I have managed to load single data attributes into the dataArray, but when it comes to the data-size which contains groups of arrays in string format, I am facing difficulties ...

What is the best way to update the content of a div on an HTML page by incorporating the content of a div from a different page using JavaScript?

I have a requirement where I need to implement a link in a Table of Contents that, upon clicking, should replace the existing content of one div on a page with the content of another div on a different page. My goal is to accomplish this using only JavaScr ...

Exploring the capabilities of JavaScript on the iOS platform

Here is the code I've written for my iOS application: webView = [[UIWebView alloc] init]; webView.delegate = self; [webView loadHTMLString:@"<script type=\"text/javascript\" src=\"myFile.js\"></script& ...

Combining two JSON objects into a single JSON object using Jquery/JavaScript

I need to combine two JSON objects into one, here are my current JSON objects: var obj_1 = { "?xml": {"version": "1.0", "encoding": "utf-8"}, "Template": { "Name": "Capital Goods-Tool and Die Maker L5 Set1", "Section": [{ "Id": "Section_ ...

Adding a detached element under certain conditions

When attempting to add a detached span based on a specific condition, I encountered the following situation. const arrow = d3 .create('span') .classed('arrow', true) .text('\u2192'); //d3.select('bod ...

Display the chosen option in the console by using onChange() function; this is analogous to how onSelect()

I'm having trouble getting the value of a select element to log in the console. I managed to do this with an onSelect() method, but the onChange() method isn't returning anything. Here's what I tried with the onChange() method: <Form.Gr ...

Troubleshooting Vue.js Error: Uncaught ReferenceError - jQuery Undefined

I'm a beginner with Vue.js and I'm attempting to develop a custom component that utilizes the jQuery formBuilder plugin from formBuilder. However, when I try to include this component file within another component, an error occurs: Uncaught Re ...