Mastering the Art of Binding Option Data from API Responses in Vue.js

Just starting out with Vue.js and attempting to bind option data from an API response.

I've made an axios call in the mounted() hook and assigned the companies data from the response, but I'm encountering errors as shown below.

    373:11  error  'companies' is not defined  no-undef
    444:7   error  'companies' is not defined  no-undef

Even though I've assigned the API response data to the company variable, it doesn't seem to be working. Can someone provide guidance?

Template Section:

    <template>
    
    ....
    
    <validation-provider
      #default="validationContext"
      name="Company"
      rules="required"
    >
      <b-form-group
        label="Company"
        label-for="company"
        :state="getValidationState(validationContext)"
      >
        <v-select
          v-model="userData.company"
          :dir="$store.state.appConfig.isRTL ? 'rtl' : 'ltr'"
          :options="companies"
          :clearable="false"
          input-id="company"
        />
        <b-form-invalid-feedback :state="getValidationState(validationContext)">
          {{ validationContext.errors[0] }}
        </b-form-invalid-feedback>
      </b-form-group>
    </validation-provider>
    
    .....
    
    </template>

Script Section:

    <script>
    import {
      BSidebar, BForm, BFormGroup, BFormInput, BFormInvalidFeedback, BButton,
    } from 'bootstrap-vue'
    import { useToast } from 'vue-toastification/composition'
    import ToastificationContent from '@core/components/toastification/ToastificationContent.vue'
    import { ValidationProvider, ValidationObserver } from 'vee-validate'
    import { ref } from '@vue/composition-api'
    import { required, alphaNum, email } from '@validations'
    import formValidation from '@core/comp-functions/forms/form-validation'
    import Ripple from 'vue-ripple-directive'
    import vSelect from 'vue-select'
    import countries from '@/@fake-db/data/other/countries'
    import store from '@/store'
    import axios from '@/libs/axios'
    
    export default {
      components: {
        BSidebar,
        BForm,
        BFormGroup,
        BFormInput,
        BFormInvalidFeedback,
        BButton,
        vSelect,
    
        // Form Validation
        ValidationProvider,
        ValidationObserver,
      },
      directives: {
        Ripple,
      },
      model: {
        prop: 'isAddNewUserSidebarActive',
        event: 'update:is-add-new-user-sidebar-active',
      },
      props: {
        isAddNewUserSidebarActive: {
          type: Boolean,
          required: true,
        },
        roleOptions: {
          type: Array,
          required: true,
        },
        planOptions: {
          type: Array,
          required: true,
        },
      },
      data() {
        return {
          required,
          alphaNum,
          email,
          countries,
        }
      },
      mounted() {
        const accessToken = JSON.parse(localStorage.getItem('userData'))
        axios.get('companies/all', {
          headers: {
            Authorization: accessToken.accessToken,
          },
        })
          .then(
            response => {
              companies = response.data
            },
          )
      },
      setup(props, { emit }) {
        const blankUserData = {
          name: '',
          username: '',
          email: '',
          password: '',
          role: null,
          currentPlan: null,
          company: '',
          country: '',
          contact: '',
        }
    
        const userData = ref(JSON.parse(JSON.stringify(blankUserData)))
        const resetuserData = () => {
          userData.value = JSON.parse(JSON.stringify(blankUserData))
        }
        const toast = useToast()
    
        // const companies = companies
    
        const onSubmit = () => {
          store.dispatch('app-user/addUser', userData.value)
            .then(
              response => {
                if (response.status === 1) {
                  emit('refetch-data')
                  emit('update:is-add-new-user-sidebar-active', false)
    
                  toast({
                    component: ToastificationContent,
                    props: {
                      title: response.message,
                      icon: 'CheckIcon',
                      variant: 'success',
                    },
                  })
                } else {
                  toast({
                    component: ToastificationContent,
                    props: {
                      title: response.message,
                      icon: 'InfoIcon',
                      variant: 'danger',
                    },
                  })
                }
              },
              error => {
                console.log(error)
              },
            )
        }
    
        const {
          refFormObserver,
          getValidationState,
          resetForm,
        } = formValidation(resetuserData)
    
        return {
          userData,
          onSubmit,
    
          refFormObserver,
          getValidationState,
          resetForm,
          companies,
        }
      },
    }
    </script>

Answer №1

To properly set up your component, make sure to define the companies array in the data function:

    data() {
      return {
        required: false,
        alphaNum : null,
        email: '',
        countries: [],
        companies: []
      }
    },

In the mounted hook, remember to access this when working with data retrieval:

    async mounted() {
      const accessToken = JSON.parse(localStorage.getItem('userData'))
      await axios.get('companies/all', {
        headers: {
          Authorization: accessToken.accessToken,
        },
      })
        .then(
          response => {
            this.companies = response.data
            this.companies = this.companies.map(c => c.label)
          },
        )
    },

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

Javascript doesn't seem to be executing properly after being echoed from PHP

I'm facing an issue where I am attempting to display some PHP code after a button click event in JavaScript, but the code is not executing and no errors are visible. <script type="text/javascript src="https://code.jquery.com/jquery- 3.4.1.min.js ...

Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling. The issue arises when I input text into the textarea and hit enter for a new line. ...

Data table created with functional components is not refreshing when columns are added or removed, which are stored in the state as an array of objects

I’ve been working on setting up a datatable with a checkbox dropdown feature to add or remove columns from the table. Everything is functioning properly, except for one issue – the table is not refreshing unless I click on one of the header titles. At ...

Obtain document via Angular 2

Is it possible to use TypeScript to download an image that is already loaded? <div *ngIf="DisplayAttachmentImage" class="fixed-window-wrapper_dark"> <button class="btn btn-close-window" (wslClick)="HideAttachmentImage()"> & ...

issue with adding string to listbox using angularjs

When attempting to add the string "New" to a list box, it is being inserted as "undefined". $http({ method: 'GET', url: 'http://xxx/api/Maintenance/GetAllFilteredItems', params: { Pt_Id: PtId} ...

Please ensure the previous v-dialog is closed before opening the next v-dialog

, I've been experimenting with a new vuetify project and have successfully added sign in and signup functionality using v-dialog. The issue I'm facing is that when I call these v-dialogs from multiple components, the previous dialog does not auto ...

Unordered calling of functions in JavaScript - is it possible?

I'm currently working on a project that involves extracting data from an SQL database and converting the output of a query (which is a number) into a corresponding color, which is then passed to a JavaScript variable. Essentially, I am using ajax to ...

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_ ...

Switch up the CSS variable within an embedded iframe

I'm in a predicament with a specific issue. I am currently utilizing Angular to incorporate an Iframe. Let's imagine the angular app as A and the Iframe as B. B is being loaded within A. Within B, I have utilized CSS variables to define colors. I ...

What is the best way to implement a fadeout or timeout for success and warning alerts in OpenCart 2.2?

Is there a way to set a timeout for alert boxes in Opencart 2.2 so that they disappear after a few seconds? I've tried the code below, but it didn't work out. Alternatively, is it possible to make the popup disappear when clicking anywhere on the ...

Create a seamless transition between point X,Y and point X1,Y1 through animated movements

Is there a way to smoothly move an image (or element) from its current X, Y position to X1, Y1? If the difference between X and X1 is equal to the difference between Y and Y1, it's straightforward. But what if the X difference is 100px and the Y diff ...

Can a specific v-bind class be activated without affecting others in VueJS and Laravel?

In my project, I have several input fields with a specific class that is triggered if the value is less than 0. Each input field functions similarly to the example below. However, I am facing an issue where when one input triggers the class, all input fi ...

Unable to retrieve innerHTML from a jQuery element

My current task involves implementing the Google Maps API. The code snippet below is what I have written so far: <div id="map"></div> To inspect the content of $("div#map"), I am utilizing the Google Chrome console. console.log($("div#map")) ...

When the mouse hovers over it, show text instead of an icon on a React Material UI button

I'm currently working on a project that involves using material ui buttons. Initially, the add button only displays the + icon. Now, I want to change the button content from the icon to the text "CREATE ITEM" when the mouse is hovered over it. Check ...

"Encountering an access denial error while trying to load a texture in JavaScript using Three.js: Restricted

I'm having trouble loading a texture in my JavaScript program using Three.js. Everything seems to be working fine with rendering a few objects, but as soon as I add the following code: var grzybSkin = THREE.ImageUtils.loadTexture('grzybuv.png&a ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Tips for steering clear of global variables while coding in JavaScript

What is the best way to avoid using global variables in JavaScript? //load more var totalItems = $("#myList li").size(); var startIndex = 3; $('#myList li:lt(' + startIndex + ')').show(); $('.loadmore').on('cli ...

Ways to conceal a message button on a website when a user logs out

I am looking for assistance with hiding the message button on my website after a user logs out. The message option should be disabled upon logout using a combination of Javascript and PHP. Can anyone help me with this issue? Below is the code for the butt ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

Troubleshooting issue with Ajax.Actionlink not canceling request using jQuery's onBegin

In the "onBegin" ajax option of an ajax.actionlink, I have a function that is called. function cancelAction() { $.ajax({ data: { p: "test", z: "value" }, url: '@Url.Action("DoSomething", "TestCtlr")', type: "GET", ...