Skip to content
Advertisement

How to bind option data from the API response in Vue.js?

I’m new to Vue.js and trying to bind option data from the API response.

I have written axios call from the mounted() and assigned companies form the response but I’m getting defined error as per below.

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

I have assigned the API response data to the company but why it’s not working so can someone guide.

Template Part:

    <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 Part:

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

Advertisement

Answer

You need to define companies in data function:

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

then in hook you need to use this:

    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)
          },
        )
    },
Advertisement