1

I'm still learning this VueJS with Laravel, what I want to do is to get the categories data from API and load it into the select dropdown, but I found that this Axios request running too long.

here's the snippet code

export default {

    data() {
        return {
            category: 0,
            categories: [],
            loading: true,
        }
    },
    async created() {
        let uri = '/api/getCategory';
        axios.get(uri).then(response => {
            this.categories = response.data;
            console.log('2');
        }).catch(error => console.log(error))
            .finally(() => {
                this.loading = false;
            });
        console.log('1');
    },
    methods: {
            loadCategories() {
            axios.get('/api/getCategory')
                .then(response => this.categories = response.data)
                .catch(error => console.log(error));
        }
    }
}

based on this. 1 DOM LOADED 2

is there a way to make my Axios API request to fetch the data first before the HTML finish loaded?

3

2 Answers 2

1

You cannot access reactive data before the created hook. Axios is made up for reactive processing which means once the data are available they will be displayed. The solutions I am suggesting are the below :

  1. You could request the data on a parent component and store it in localStorage for example. You could use it anywhere in the application then.
  2. Keep your code in the created hook. Use a computed property instead of categories for instant rendering.

    computed:{ computedCategories(){ return this.categories; } }

  3. You definitely have to check your server side code for query enhancement.

Sign up to request clarification or add additional context in comments.

Comments

0

If you're not able to reduce the response time of the request, I suggest you implement some kind of visual loading indication, maybe on the select input. Could be a spinner or a small "Loading..." text.

Having the request in a parent component for example, won't make up for the fact that the request response time is slow and will be a bad experience for the user, with no indication that the component is loading/fetching data.

If the problem is that you get render errors, because categories is not yet available to the DOM, you can use a conditional render v-if="categories.length", to only render the elements with data, when it's available.

Comments

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.