0
votes

I am using Axios to make HTTPS calls to the twitter API and return tokens and tweets:

TwitterScreen.js:

export default class TwitterLogin extends React.Component {
  async componentDidMount(){
      await init("<CUSTOMER KEY>", "<CUSTOMER SECRET KEY>");
      this.twitter =  await getToken();
      alert(this.twitter);
  }
  render() {
      return(
      <View style= {styles.container}>
          <Button
          title="Twitter Login Button" onPress={this.twitter)}
          />
      </View>
     )
  }
}

AxiosUtility.js:

export function init(cuskey, seckey){
    axios.defaults.baseURL = 'https://api.twitter.com';
    //TODO: RFC 1738 this. 
    axios.defaults.headers.common['Authorization'] = 'Basic ' + btoa(cuskey + ':' + seckey);
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    axios.defaults.headers.post['Accept-Encoding'] = 'gzip';
}

export function getToken(){
    axios.post('/oauth2/token', 'grant_type=client_credentials', {
        'User-Agent' : 'whereabouts dev',
        Accept: '*/*',
    })
    .then((response) => {
        console.log(response.data);
        return (response.data);
    })
    .catch((error) =>{
        console.log(error)
    }
    )
} 

When console.log(response.data) runs, it returns a successful message. But it runs after an alert message is sent to the app, meaning that the alert message says "Undefined". I followed the documentation to no avail.

I also get a warning saying, "await has no effect on the type of this expression". How do I properly utilize await and async so the alert happens after twitter is called?

2
You need to return a promise from your getToken function, put a return before the axios request.Rohit Kashyap

2 Answers

2
votes

getToken must return the promise i think.

export function getToken(){
//do not return void but promise with return
   return axios.post('/oauth2/token', 'grant_type=client_credentials', {
        'User-Agent' : 'whereabouts dev',
        Accept: '*/*',
    }).then((response) => {
        console.log(response.data);
        return (response.data);
    })
    .catch((error) =>{
        console.log(error)
    }
    )
}
0
votes

I noticed this recently. await doesn't work on componentDidMount(). suggestion : do your await inside some other function and that should work.