Import React
import React from 'react';
Create Class
Class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
list: null,
error:false
}
}
Create componentDidMount to fetch data from API
componentDidMount() {
fetch("http://localhost:3000/example")
.then(res => res.json())
.then(
(result) => {
this.setState({
listen:result,
isLoaded: true
});
},
(error) => {
this.setState({
error: true,
isLoaded: true
})
}
)
}
Render component & Post request (I am requesting Post & Get at the same time so I can keep up the new data after Post request)
render() {
const postRequest = (data) => {
let requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};
fetch("http://localhost:3000/example", requestOptions)
fetch("http://localhost:3000/example")
.then(res => res.json())
.then(
(result) => {
this.setState({
list: result,
isLoaded: true
});
},
(error) => {
this.setState({
error: true,
isLoaded: true
})
}
)
}
const { error, isLoaded, list } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>Hello, World~!</div>
);
}
}
}
export default App;
Top comments (0)