1

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>

1 Answer 1

2

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)
          },
        )
    },
Sign up to request clarification or add additional context in comments.

7 Comments

I have tried but I'm getting errors in console [Vue warn]: Invalid prop: type check failed for prop "options". Expected Array, got Object found in
Results are showing in the log but getting errors in console.
according to error your result is object, you need to convert it to array
I am getting data like {"value":1,"label":"Raynor and Sons"},{"value":2,"label":"Robel Ltd"},{"value":3,"label":"Ankunding LLC"}
You can map your result: this.companies = this.companies.map(c => c.label) , I updated answer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.