Skip to content

Instantly share code, notes, and snippets.

@MaraAlexa
Last active October 4, 2017 16:40
Show Gist options
  • Save MaraAlexa/0951af91b66d7e034f2e4409c5d966f6 to your computer and use it in GitHub Desktop.
Save MaraAlexa/0951af91b66d7e034f2e4409c5d966f6 to your computer and use it in GitHub Desktop.
consume an endpoint with axios and put the data into state
import React from 'react'
import axios from 'axios'
const endpoint = 'https://raw.githubusercontent.com/ongithub/products/gh-pages/products.json'
class ProductList extends React.Component {
state = {
allProducts: []
}
// when component is mounted => fetchData
componentDidMount() {
this.fetchData()
}
fetchData = () => {
axios.get(endpoint)
.then((response) => {
console.log(response);
this.setState({
allProducts: response.data
})
})
.catch(function (error) {
console.log(error);
});
}
render(){
return(
<div>
<h6>List of products</h6>
<ul className='products'>
{
this.state.allProducts.map((product) =>
<li key={product.id}>
<Product product={product}/>
</li>
)
}
</ul>
</div>
)
}
}
export default ProductList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment