I'm trying to get a data that is returning from axios get method to a method call on aon object. Instead of returning the value, it's returning the promise. What am I missing here?
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import "./styles.css";
class App extends Component {
state = {
totalResults: ""
};
componentDidMount() {
this.setState({
totalResults: this.fetchData()
.then(function(res) {
const r = res.data.totalResults;
return r;
})
.catch(err => console.log("error: ", err))
});
}
fetchData = () => {
return axios.get(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=8d98dac05ec947d1b891832495641b49"
);
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={() => console.log(this.state.totalResults)}>
Click
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here's the link to codesandbox
Note: This is just a reference code. I can't do setState because I'm trying to call the method from array.map() iterator instead.
Edit:
This is what actually I'm trying to do: codesandbox.io/s/n5m3qyn65l
For some reason it's showing Network Error
Thanks for helping me out.