0
votes

i'm trying to fetch data from local with axios. But the fetch function is in another file. when i trying to print the response it returns undefined.

this is function file all_products.js

export default async function getAllProducts() {
    await axios.get('http://10.0.2.2:3006/posts')
   .then(response => {
        const items = response.data;
        return items;
    })
 .catch({});
}

and this is homepage where i trying to fetch data

constructor(props) {
    super(props)
    this.state = {
        data: []
    }
}
componentDidMount() {
    getAllProducts().then((d) => this.setState({ data: d }))
}

here i'm trying to console log in render function

render() {
    console.log("render : " + this.state.data)
...

and this is result

LOG  render :
LOG  render : undefined
1
when you add log to items in axios.get what you get? - Buggies
items : [object Object],[object Object] i can see data in function but when i'm trying to separete this is happening - ba_rt

1 Answers

0
votes

Try this syntax:

export default async function getAllProducts() {
    await axios.get('http://10.0.2.2:3006/posts')
        .then((response) => {
            return response.data;
        })
        .catch((error) => console.log(error));
}