<head>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root4"></div>
<script type="text/babel">
const url = "https://jsonplaceholder.typicode.com/posts";
class App4 extends React.Component {
constructor(props) {
super(props);
this.state={
data:[],
loading:false,
error: null,
error_message:"",
}
}
handle_click() {
this.setState({ loading: true });
fetch(url)
.then(response => response.json())
.then((data) => this.setState({ data: data, loading:false }))
.catch((error) => this.setState({ error: false, error_message:error.message }));
}
render(){
const data_array = this.state.data.map(
(item,index)=>{
return(
<tr key={index}>
<td>{item.userId}</td>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.body}</td>
</tr>
);
}
);
const status = this.state.loading? "loading": "";
return(
<div>
<p>{status} data from {url}</p>
<p>{this.state.error_message}</p>
<button onClick={()=>this.handle_click()}>fetch data</button>
<table>
<tbody>
{data_array}
</tbody>
</table>
</div>
);
}
}
ReactDOM.render(
<App4 />,
document.getElementById('root4')
);
</script>
</body>
No comments:
Post a Comment