Home > other >  React Native Axios return undefined from another file
React Native Axios return undefined from another file

Time:07-29

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

CodePudding user response:

The problem occurs because you don't return the promise from your axios call inside the function, that's why it returns undefined, nothing returns. The promise just resolves and that's it, you have to return the value from the function.

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

also i'd suggest to rewrite this function to async await syntax, so you don't mix promises chaining and async await.

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

if you want to catch errors, you can wrap it in trycatch block

export default async function getAllProducts() {
    try {
       const response = await axios.get('http://10.0.2.2:3006/posts')
       const items = response.data
       return items
    } catch (err) {}
}
  • Related