-
-
Save hemepositive/942d751b366698799dae9f7a72d3ac49 to your computer and use it in GitHub Desktop.
Pattern: setState with callback API call and Conditional rendering
This file contains hidden or 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
// https://hackernoon.com/do-more-with-less-using-render-props-de5bcdfbe74c | |
export default class CarsList extends React.Component { | |
state = { | |
cars: [], | |
isLoading: false, | |
}; | |
_fetch = async () => { | |
const res = await fetch("api/url"); | |
const json = await res.json(); | |
this.setState({ cars: json, isLoading: false }); | |
}; | |
componentDidMount() { | |
this.setState({ isLoading: true }, this._fetch); | |
} | |
render() { | |
const { cars, isLoading } = this.state; | |
return ( | |
<div> | |
<h3>My cards</h3> | |
{isLoading && <p>Loading cards m8</p>} | |
{cars.length > 0 && ( | |
<ul> | |
{cars.map(car => ( | |
<li key={car.id}> | |
{car.title} | |
</li> | |
)} | |
</ul> | |
)} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment