When Vue detects a change in declared parameters from an empty string, it automatically sends a

Within my application, I am making a request to the backend app and receiving a response with an ID such as { 'id': '12345'}. This ID is then saved as loadId within the data object:

export default {
  name: 'SyncProducts',
  data() {
    return {
      loadId: '',

Now, I need to send another POST request named fetchSyncedProductsResultRequest whenever the loadId in the data changes from empty. How can I achieve this?

Below is the code snippet:

imports.js

const createApparelMagicProductsRequest = (self, products) => {
  const jwtToken = self.$store.state.idToken;
  console.log(products)
  console.log()
  const payload = JSON.stringify({ product_codes: products['product_codes'].split(',') })

  return axios
    .post(`/api/v1/imports/products_batches`, payload,{
      headers: {
        Authorization: `Bearer ${jwtToken}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    .then(response => response.data['id'])
};

const fetchSyncedProductsResultRequest = (token, id) => {
  return axios
    .get(`/api/v1/imports/products_batches`, {
      params: { id: id },
      headers: {
        Authorization: `Bearer ${token}`,
      }
    })
    .then(response => {
      return response.data['result']
    })
};

sync_products.vue

<script>

import {
  fetchSyncedProductsResultRequest,
  createApparelMagicProductsRequest
} from '../../api/imports'

export default {
  name: 'SyncProducts',
  data() {
    return {
      styleCodes: [],
      fetchedProductSyncResult: [],
      loadId: '',
    }
  },
  async mounted() {
    await fetchSyncedProductsResultRequest(this, load.id)
    this.syncedProductsFetched = true
    this.pageChanged(this.currentPage)
  },
  async mounted() {
    const jwtToken = this.$store.state.idToken;
    fetchSyncedProductsResultRequest(jwtToken).then(data => {
      this.fetchedProductSyncResult = data
    })
  },


</script>

Answer №1

To ensure that the

fetchSyncedProductsResultRequest()
function is called when the value of loadId changes from an empty string to a non-empty string, you can utilize a watcher:

export default {
  watch: {
    loadId(newValue, oldValue) {
      if (!oldValue && newValue) {
        const jwtToken = this.$store.state.idToken;
        fetchSyncedProductsResultRequest(jwtToken, newValue).then(data => {
          this.fetchedProductSyncResult = data
        });
      }
    }
  }
}

Check out the demo for more information.

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

Utilizing global variables in Electron applications with Vue and Webpack

I have been struggling for hours to make global variables work in electron using webpack and vue, but Vue is unable to locate the declared variable. webpack.config.js { test: /\.scss$/, use: [ "vue-style-loader", "css-loader", ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Error encountered on Windows 10 version 10.0.19044 during library installation with npm

I've encountered an error while trying to run or install libraries for a project within our organization. E:\GIT\bookshelf>npm install npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

Switching the cursor to an image when hovering over an element is causing inconsistency in hover events triggering

Currently, I am attempting to implement an effect that changes the cursor to an image when hovering over a text element and reverts back to the normal cursor upon leaving the text element. However, this functionality is not working as expected when using R ...

Is there a built-in method or library for extracting data from JSON strings in programming languages?

Duplicate Query: how to parse json in javascript The data sent back by my server is in JSON format, but it doesn't follow the usual key/value pairs structure. Here's an example of the data I'm receiving: ["Value1","Value2","Value3"] ...

How to target and manipulate a specific element in the DOM using VueJS

One thing that puzzles me is how to efficiently select a specific element in the DOM using VueJS, with or without jQuery. Within my component, I've created a method function that performs the following task: $(".u-loc input").focusin(function() { ...

VueJS - Create a dynamic timer using setInterval function

I have a function that is initially triggered within the 'mounted' lifecycle hook, and then it continues to be called every 15 minutes. In my component, I am looking to showcase a countdown until the next setInterval in minutes and seconds. asyn ...

Verify the status of the mongodb server synchronously

Is there a method to detect if a mongod instance is still operational while using mongoclient? In my mongoclient module, I have implemented a db.on('close') handler which functions properly when mongod exits normally. However, if the server proc ...

Implementing a dynamic loading strategy for Google reCAPTCHA based on language selection

I have a unique application that requires the selection of one language out of four options (English, French, Dutch, español) in a form. Below the language selection, the Google reCaptcha is displayed. I am looking to dynamically load the reCaptcha scrip ...

Steps for resetting a div's display after adjusting the device size

I have a code that displays horizontally on desktop screens and vertically on phones. It includes an x button (closebtn) that is only displayed on phones to close the menu bar. How can I automatically display it again after resizing the page back to deskto ...

Encountering an unhandled promise rejection issue with Knex's batchInsert function when attempting to insert arrays larger than 3 elements

I am currently working on an express app and utilizing Knex as the query string builder. During batch insert operations with an array of 1000+ objects, I encountered an error when the array exceeded a certain length. The specific error message is provided ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

HTML pages are free from any visible banner ads

There is a file named banners.js function addEvent(object, evName, fnName, cap) { if (object.attachEvent) object.attachEvent("on" + evName, fnName); else if (object.addEventListener) object.addEventListener(evName, fnName, cap); } ...

The calculator I designed using HTML, CSS, and JavaScript is experiencing difficulty adjusting to various screen sizes

I recently built a calculator using HTML, CSS, and JavaScript. It works perfectly on PC or big screens, but when viewed on smaller devices like phones or tablets, the display gets cut off and does not adjust properly. Here are some example pictures for ref ...

What is the method to utilize global mixin methods within a TypeScript Vue component?

I am currently developing a Vue application using TypeScript. I have created a mixin (which can be found in global.mixin.js) and registered it using Vue.mixin() (as shown in main.ts). Content of global.mixin.js: import { mathHttp, engHttp } from '@/ ...

What is the best method to obtain the following id for an image?

Whenever I hover over the li with the number 3, I am getting the wrong number for the next id in the img tag. The first time, I get next id = 4 which is incorrect. But on the second hover, I get next id = 0 which is what I actually need. How can I correctl ...

The process of converting a response into an Excel file

After sending a request to the server and receiving a response, I am struggling with converting this response into an Excel file. Response header: Connection →keep-alive cache-control →no-cache, no-store, max-age=0, must-revalidate content-dispositio ...

Ways to reduce the amount of time spent watching anime when it is not in view

My anime experiences glitches as the black container crosses the red, causing a decrease in duration. Is there a way to fix this glitch? I attempted to delay the changes until the red path is completed, but the glitches persist. delayInAnimeSub = ourVilla ...