0

I am working on a laravel project with vue components. When i do a get request with axios in my component i cant set the data variable to the response. these are my methods:

    methods: {

    location ()
    {

        console.log('location')

    },

    getCategories () {

        axios.get(this.baseUrl + '/api/search/categories').then((response) => {

            this.categories = response.data

            console.log(response.data)

        }).catch((e) => {

            console.log(e)

        })

    }

}

Here is my data()

    data() {

    return {

        searchTitle: null,
        searchLocatie: null,
        searchCategorie: null,
        categories: [],
        //baseUrl: 'https://sdinbeeld.frb.io/',
        baseUrl: 'http://localhost:8888/sdinbeeld/public/'

    };

},

I want to set this.categories equal to response.data

but when i do console.log(this.categories) in the mounted() section it returns just an empty array

Does someone know ho to fix this?

2 Answers2

1

This is happening because the mounted hook is fired before the HTTP request has finished. So at that point, it is still an empty array. This is because Ajax requests are asynchronous. Meaning code can still execute while the request is in progress. Within your getCategories() method, if you change the code to this:

axios.get(this.baseUrl + '/api/search/categories').then((response) => {

        this.categories = response.data

        console.log(response.data);
        console.log(this.categories);

    }).catch((e) => {

        console.log(e)

    })

You will see it will log out the correct value once the request has finished.

George Hanson
  • 2,940
  • 1
  • 6
  • 18
0

because axios.get return a promise which is a asynchronous action, thus you can not get the new value below the this.getCategories()

you can do this

methods: {
  async getCategories() {
    try {
      const response = await axios.get(this.baseUrl + '/api/search/categories');
      this.categories = response.data;
      console.log(response.data);
    } catch (e) {
      console.log(e);
    }
  },
},
async mounted() {
  await this.getCategories();
  console.log(this.categories);
},
masongzhi
  • 164
  • 1
  • 6