- Create Components folder under src folder
- Add FetchDataLoadingErrorHandling.js file and add below Code
import React, { Component } from "react";
const API = "https://hn.algolia.com/api/v1/search?query=";
const DEFAULT_QUERY = "redux";
class FetchDataLoadingErrorHandling extends Component {
constructor(props) {
super(props);
this.state = {
hits: [],
isLoading: false
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch(API + DEFAULT_QUERY)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Something went wrong ...");
}
})
.then(data => this.setState({ hits: data.hits, isLoading: false }))
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
const { hits, isLoading, error } = this.state;
if (error) {
return <p>{error.message}</p>;
}
if (isLoading) {
return <p>Loading ...</p>;
}
return (
<ul>
{hits.map(hit => (
<li key={hit.objectID}>
<a href={hit.url}>{hit.title}</a>
</li>
))}
</ul>
);
}
}
export default FetchDataLoadingErrorHandling;
- Open index.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import FetchDataLoadingErrorHandling from "./Components/FetchDataLoadingErrorHandling";
function App() {
return (
<div className="App">
<FetchDataLoadingErrorHandling />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Output:
No comments:
Post a Comment