0

I'm learning React and able to pull API data inside of my various components.

I make Axios calls like this:

componentDidMount(){
    axios.get("https://api.someurl.com/some-request/").then((response)=>{
        this.setState(()=>{
           return {
             mydata: response.data
           }
        })
    })
}

This all works so my next step is to move the API calls to an external function/file and pass parameters to make the API calls reusable. This is mainly because the API needs to be secured with authorization headers, time stamps, etc. so I'd like it all done in one place. Although I can't seem to find the right approach.

What I'm trying to do:

// Inside of components:
componentDidMount(){
  this.setState(()=>{
   return {
     mydata: externalFunction({this.state.someArg})
   } 
  })
}

// Some external module
function externalFunction(args) {
  // create authorization header, make call
  return { "name":"John", "age":25, "city":null }
}

Should the external module be React class (I don't need state - it's just JSON data), a react function or can I simply use a JavaScript function? No matter what I try it seems the return values of the Axios calls are undefined. Again, I'm new to this so probably missing something critical...

Any example would be appreciated. Thanks.

chris358
  • 139
  • 5

1 Answers1

2

Axios calls are async. You can not immediately return something from them. If you want to provide a function to wrap your api request it has to accept a callback as a parameter which gets called when the request finished. Only then you can call setState with these data:

// Inside of components:
componentDidMount(){
  fetchData({this.state.someArg}, data => this.setState({data});
}

// Some external module
function fetchData(args, callback) {
  axios.get(/* use args here... */).then(response => callback(response.data))
}

Alternatively (and probably better) your external function returns a Promise:

// Inside of components:
componentDidMount(){
  fetchData({this.state.someArg})
      .then(data => this.setState({data})
      .catch(error => console.log(error));
}

// Some external module
function fetchData(args, callback) {
  return new Promise((resolve, reject) => {
     axios.get(/* use args here... */)
         .then(response => resolve(response.data))
         .catch(error => reject(error));
  });
}
trixn
  • 15,761
  • 2
  • 38
  • 55