<main></main>
function swapiClient(baseUrl) {
return function(Component) {
return class SwapiClient extends React.Component {
constructor(props) {
super(props);
this.state = { loading: false };
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.id !== this.props.id) {
this.fetchData();
}
}
componentDidMount() {
this.fetchData();
}
fetchData() {
this.setState({ loading: true });
const { id } = this.props;
$.get(`${baseUrl}/${id}`).then(res => {
this.setState({
data: res,
loading: false,
})
});
}
renderLoading() {
return <p>Loading data for id: {this.props.id}</p>
}
render() {
const { data } = this.state;
if (this.state.loading) {
return this.renderLoading();
} else {
return <Component data={data} />
}
}
}
}
}
@swapiClient('https://swapi.co/api/people')
class Person extends React.Component {
render() {
const { data } = this.props;
if (!data) { return false; }
return (
<div>
<p><b>Name:</b> {data.name}</p>
<p><b>Gender:</b> {data.gender}</p>
</div>
)
}
}
@swapiClient('https://swapi.co/api/films')
class Film extends React.Component {
render() {
const { data } = this.props;
if (!data) { return false; }
return (
<div>
<p><b>Title:</b> {data.title}</p>
<p><b>Director:</b> {data.director}</p>
</div>
)
}
}
class App extends React.Component {
render() {
return (
<div>
<Person id={1} />
<Person id={2} />
<Film id={2} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('main'));
View Compiled
This Pen doesn't use any external CSS resources.