Home > Blockchain >  Vue send request when declared params changed from empty string
Vue send request when declared params changed from empty string

Time:05-24

In my app I'm sending a request to my backend app from which I get a response with id like { 'id': '12345'}. I saves this id as loadId inside data, here:

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

Now I want to send another POST fetchSyncedProductsResultRequest when this data loadId change from empty. How to do so?

Below my code:

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>

CodePudding user response:

Use a watcher on loadId that calls fetchSyncedProductsResultRequest() with the new value if it's changed from an empty string to a non-empty string:

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

demo

  • Related