How to utilize Vue.js for making a GET request by including an ID as a path parameter

My goal is to make a GET request to my backend application and pass an ID as a query parameter. The endpoint I want to use is -

GET    /api/v1/imports/products_batches/:id
. Below is the code I have written:

imports.js

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

<template>
  <div>
    <div class="col-12 col-md-3">
      <button
        type="button"
        class="btn btn-primary"
        @click="syncProducts"
      >
        Sync
      </button>
    </div>
  </div>
</template>

<script>

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

export default {
  name: 'BackboneSyncProducts',
  data() {
    return {
      fetchedProductSyncResult: [],
    }
  },
  methods: {
    async syncProducts() {
      let confirmationText = `Do you want to ${this.productsToSyncAmount} sync products?`

      if (this.productsToSyncAmount === 0) {
        ModalController.showToast('', 'Type product codes for sync first, please!', 'warning')
      }
      else if (await ModalController.showConfirmation('Confirmation', confirmationText)) {
        try {
          ModalController.showLoader()
          await fetchSyncedProductsResultRequest(this, '43').then(data => {
            console.log(data)
            this.fetchedProductSyncResult = data
          })
          // await createApparelMagicProductsRequest(this, this.styleCodes).then(data => {
            // this.loadId = data['id']
          // })
          const successMessage = `${this.productsToSyncAmount} products have been queued for sync`
          await ModalController.showToast('', successMessage)
        } catch (data) {
          const errorMessage = `Error occurred during queueing products to sync - `
          ModalController.showToast('', errorMessage + data?.message, 'error')
        } finally {
          this.styleCodes = []
          ModalController.hideLoader()
        }
      }
    },
  }
}
</script>

In the code, I have hardcoded id=43 and added a console.log statement here:

          await fetchSyncedProductsResultRequest(this, '43').then(data => {
            console.log(data)
            this.fetchedProductSyncResult = data
          })

However, it is returning undefined.

I am unsure if I am passing the query parameters incorrectly or if there is a typo in my code. How can I correct this and send the request successfully?

Answer №1

Substitute your

fetch
    .post(`/api/v1/imports/items_groups`, ...

for

fetch
    .post(`/api/v1/imports/items_groups/${id}`, ...

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

Error message encountered when attempting to export functions in Reactjs, resulting in an undefined function error in the context of Reactjs

As I work on creating an adaptive menu using Reactjs and Material UI, I have managed to complete everything. However, I encountered an issue when trying to import a const defined in a different file as the functions are not functioning as expected. The fu ...

Backbone.js experiencing synchronization issues exclusively in Internet Explorer

Can anyone confirm if they have encountered this issue before? I'm unsure how to elaborate further as it seems to be the only symptom. Additionally, it does not sync correctly in Internet Explorer. ...

Seeking assistance with changing the pages

Looking for assistance with troubleshooting my function. All variables are accounted for. var swith = document.getElementById("sub"); var one = document.getElementById("rule"); var two = document.getElementById("cool"); var three = document.getElementByI ...

How to Activate Child Component in Vue When Submitting a Form

This is my PhoneLineNumberComponent. Everything is working perfectly, but I'd like to have the child component form loaded when the user clicks the button on the parent component. The PhoneLineNumberComponent is the child component, and the Bu ...

After mapping in JavaScript, delete the property name

Is there a way to exclude the property name from the returned value? I want to eliminate the property name "projects: [ ]" from the output. router.get("/", (req, res, next) => { Project.find() .exec() .then(docs => { res.status(200) ...

Troubleshooting the challenges with jQuery's next().addClass() and prev().addClass() functions

I am attempting to create a slider feature. I have four different contents that I've positioned consecutively, but made them invisible initially. I defined a class called active-client with the attribute display: flex. Using jQuery's addClass() m ...

What's the Catch with Vue's Named Slots?

When working with Named Slots in Vue (using the older, more verbose API for component slots), if there is a reusable component with a template structured like this: <template> <div v-for="field in formFields"> <slot name="`${field.key}_P ...

What is the best way to add an element while preserving its original placement?

I need a solution to duplicate the code of an element and transfer it to another element without removing it from its original position. Currently, I have a JavaScript function that allows you to move a picture to a box when it's clicked. However, th ...

What is the best way to deactivate a button when not all inputs require filling?

I need to make a change in my form where I want to disable a button, but not all the inputs are mandatory. Even though I have specified which inputs need to be filled in the code, I still have to fill all the inputs in the form. How can I modify this? $ ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

Is there an XML File Wrapper to Generate PDF Output?

Greetings Forum Members, I have been given the responsibility of creating a PDF file from multiple XML files. Has anyone come across an XML wrapper file before? This type of file would essentially contain a list of all the source XML file names in a spec ...

Issue encountered: Document not being saved by Mongoose, error message received: "MongoClient connection must be established"

Currently, I am attempting to establish a connection with MongoDb using mongoose. Below is the code snippet that I have implemented for this purpose: controller.js const conn = mongoose.createConnection(db, { useNewUrlParser: true, ...

What are the various jQuery methods that can be utilized in the object parameter of a jQuery element creation request?

According to a post by John Resig on his website at http://ejohn.org/apps/workshop/adv-talk/#3, it is mentioned that methods can be attached using the object parameter. While 'text' appears to function correctly, any other content in the object ...

What purpose does @ViewChild serve if we are unable to modify or interact with its properties from the Parent Component?

I have two main components - home and about. Within both of these, I am including a third component called hearts. Currently, I am manipulating the value of the 'age' property in the hearts component (initially set to '23') using @ViewC ...

retrieve the most recent file following a $group operation

I am currently utilizing the official MongoDB driver specifically designed for Node.js. This is how my message data is organized. Each post consists of a timestamp, a user ID, and a topic ID. [ { "_id" : ObjectId("5b0abb48b20c1b4b92365145"), "t ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

Comparison between WAMP and Live server integration with Facebook for connecting applications

I've been facing some challenges while integrating my website with Facebook Connect. I have been following the instructions provided in this guide. When attempting to run the following code from localhost, please note that for security reasons, my ap ...

How to Pass and Execute Asynchronous Callbacks as Props in React Components

I'm curious about the correct syntax for passing and executing async calls within React components. Specifically: Many times, I'll have a function that looks like this: const doAsync = async (obj) => { await doSomethingAsync(obj) } ...and ...

Make your CSS and JS files smaller by using a PHP compression script in your WordPress child theme

  I am looking to implement a PHP script that will serve combined, pre-gzipped, and minified JS and CSS files. You can find the source code for this script here: https://code.google.com/p/compress/ I have a WAMP localhost with WordPress install ...

What could be causing the React state to not function properly when using data from an external class?

Recently diving into the world of Javascript and React, I decided to challenge myself by creating a basic calculator. My strategy was to separate the calculator logic into its own class. As I am currently testing it out, I encountered a peculiar issue. It ...