Skip to content

Instantly share code, notes, and snippets.

@dearshrewdwit
Created September 28, 2020 13:20
Show Gist options
  • Save dearshrewdwit/952658dba2e4a064ad554546bbafa2bd to your computer and use it in GitHub Desktop.
Save dearshrewdwit/952658dba2e4a064ad554546bbafa2bd to your computer and use it in GitHub Desktop.
// using class component and lifecycle method to manage lifecycle event: ComponentDidMount
import React, { Component } from 'react'
class Headlines extends Component {
constructor(props) {
super(props)
this.state = { items: [] }
}
componentDidMount() {
fetch("http://news-summary-api.herokuapp.com/guardian?apiRequestUrl=http://content.guardianapis.com/search?q=coronavirus")
.then(response => response.json())
.then(data => {
this.setState({items: data["response"]["results"]})
})
}
render() {
return (
<div className="headlines">
{this.state.items.map((item, index) => <a href={item["webUrl"]}>{item["webTitle"]}</a>)}
</div>
)
}
}
export default Headlines
// using effect hook to manage lifecycle event: ComponentDidMount
import React, { useState, useEffect } from 'react'
const Headlines = () => {
const [items, setItems] = useState([])
useEffect(() => {
fetch("http://news-summary-api.herokuapp.com/guardian?apiRequestUrl=http://content.guardianapis.com/search?q=coronavirus")
.then(response => response.json())
.then(data => setItems(data["response"]["results"]))
}, [])
return (
<div className="headlines">
{items.map(item => <a href={item["webUrl"]}>{item["webTitle"]}</a>)}
</div>
)
}
export default Headlines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment