0

In React-Native

Problem

I am trying to make re-usable function for Axios/Fetch(GET) request in consts.js file and calling from App.js file but when I pass response of Axios/Fetch(GET) request in App.js file it's always get undefined in App.js

Consts.js

import axios from 'axios'

const axios_get = (trail_url, token) => {

    axios({
        method: 'GET',
        url: 'https://....' + trail_url,
        headers: { 'Authorization': 'Bearer ' + token }
    }).then((res) => {
        _resData(res)
        // get reponse object here
    }).catch((e) => {
        console.log('Error', e)
    }).finally(() => {
        console.log('req done')
    })

}

const _resData = (data) => {
    // also get response object here
       return data

    // also try
       return Object(data)
}

export { axios_get, _resData }

App.js

import React from "react"
import { axios_get, _resData } from './Consts'

export default class App extends React.Component {


    componentDidMount = async () => {
        //api calling 
        axios_get('Dummy_trail_url', 'Dummy_Token')
        // above api called successfully

        // now when i try to get res from it's show always undefined
        //  reponse object of retrun 
        _resData()
        // also try
        var temp = new _resData()
        // but always it's got undefined
    }

}

So how do I get the return response of Axios/fetch from Consts.js file to App.js file from function while calling API?

Hardik Desai
  • 1,089
  • 12
  • 20
  • you are exporting the function _resData and not the result itself. – Tinu Jos K Feb 04 '20 at 13:25
  • You're returning `data` to the `then` function and then not doing anything with it. – JDunken Feb 04 '20 at 13:25
  • try that but got 'await' has no effect on the type of this expression – Hardik Desai Feb 04 '20 at 13:25
  • Calling `_resData` from inside of `axios_get` is different than calling `_resData` again somewhere else - these are two separate calls that are executed independently. This is why you're getting `undefined` when you call `_resData()` with no arguments - it's because passing nothing to a function is like passing `undefined` to it. – goto Feb 04 '20 at 13:26
  • @JDunken calling in App.js – Hardik Desai Feb 04 '20 at 13:27
  • @goto1 also try that but got undefined – Hardik Desai Feb 04 '20 at 13:28
  • @DevAelius I'd like to know what you're really trying to accomplish here. – goto Feb 04 '20 at 13:28
  • @DevAelius try what? What you're doing right now is like calling a function on two separate occasions, these calls are independent of each other, and it won't work the way you're thinking it should work. – goto Feb 04 '20 at 13:29
  • You're calling `_resData` without any arguments from app.js and yet it is defined to take a `data` parameter. And when the request returns you're not doing anything with `data` just passing it around. What do you expect to happen? – JDunken Feb 04 '20 at 13:31

0 Answers0