Skip to content

Instantly share code, notes, and snippets.

@hemepositive
Forked from JoaoCnh/CarsList.js
Last active July 17, 2018 14:18
Show Gist options
  • Save hemepositive/942d751b366698799dae9f7a72d3ac49 to your computer and use it in GitHub Desktop.
Save hemepositive/942d751b366698799dae9f7a72d3ac49 to your computer and use it in GitHub Desktop.
Pattern: setState with callback API call and Conditional rendering
// 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