Last active
October 4, 2017 16:40
-
-
Save MaraAlexa/0951af91b66d7e034f2e4409c5d966f6 to your computer and use it in GitHub Desktop.
consume an endpoint with axios and put the data into state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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