API

Get data from external API

const url = "YOUR_API"
async function getArticles() {
  let result = await fetch(url).then(response => response.json());
  return result.articles;
}

From the sample code, we used async function to fetch data from API

How to use it ?

constructor(props){
  super(props);
  this.state = { articles: [], isLoading: true };
}

componentDidMount() {
  this.fetchData();
 }

fetchData() {
  getArticles()
    .then(articles => this.setState({ articles, isLoading: false }))
    .catch(() => this.setState({error, isLoading: false }));
}

As you see, the function will be launch in componentDidMount. After that, we set those data into our state.

Last updated