Component Lifecycle componentDidMount

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { Component } from "react";
import { withRouter } from "react-router-dom";

class Details extends Component {
constructor() {
super();
this.state = { loading: true };
}

async componentDidMount() {
const res = await fetch(
`http://pets-v2.dev-apis.com/pets?id=${this.props.match.params.id}`
);
const json = await res.json();
this.setState(Object.assign({ loading: false }, json.pets[0]));
}

render() {
console.log(this.state);

if (this.state.loading) {
return <h2>loading … </h2>;
}

const { animal, breed, city, state, description, name } = this.state;

return (
<div className="details">
<div>
<h1>{name}</h1>
<h2>{`${animal}${breed}${city}, ${state}`}</h2>
<button>Adopt {name}</button>
<p>{description}</p>
</div>
</div>
);
}
}

export default withRouter(Details);

To replace the ctr

1
2
# so we can replace the constructor in React.Component class
npm i -D @babel/plugin-proposal-class-properties@7.13.0 @babel/preset-env@7.13.5 @babel/eslint-parser@7.13.4

Then replace

1
2
3
4
constructor() {
super();
this.state = { loading: true };
}

With

1
state = { loading: true };