null
null

Reputation: 53

api request returns undefined

maybe is a stupid question but, when I'm calling api from 'outside' function it always returns undefined, for example:

actions.js

import axios from 'axios'

export function getProducts() {
    axios.get('http://localhost:8000/api/products').then((response) => {
        return response;
    });
}

and then in a component:

mounted() {
        this.products = getProducts();
        console.log(this.products);
    }

returns undefined

of course when I make a request from component it returns result

mounted() {
        axios.get('http://localhost:8000/api/products').then((response) => {
            this.products = response;
            console.log(this.products);
        });
    }

Why is this happening and how can I solve this problem?

Thanks

Upvotes: 2

Views: 2800

Answers (1)

thanksd
thanksd

Reputation: 55674

You are returning the response value in the then callback of the axios.get call. However, your getProducts function doesn't return anything.

Simply return the axios.get call:

export function getProducts() {
  return axios.get('http://localhost:8000/api/products');
}

Then, the result of getProducts will be the Promise returned by axios.get(). So, you can add a then callback on the result of getProducts and set you this.products that way:

mounted() {
  getProducts().then(products => this.products = products);
}

Upvotes: 3

Related Questions