- Create Components folder under src folder
- Add AxiosLoadingErrorHandling.js file and add below Code
import React, { Component } from "react";
import axios from "axios";
const API = "https://hn.algolia.com/api/v1/search?query=";
const DEFAULT_QUERY = "redux";
class AxiosLoadingErrorHandling extends Component {
constructor(props) {
super(props);
this.state = {
hits: [],
isLoading: false,
error: null
};
}
componentDidMount() {
this.setState({ isLoading: true });
axios
.get(API + DEFAULT_QUERY)
.then(result =>
this.setState({
hits: result.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 AxiosLoadingErrorHandling;
- Open index.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import AxiosLoadingErrorHandling from "./component/AxiosLoadingErrorHandling";
import "./styles.css";
function App() {
return (
<div className="App">
<AxiosLoadingErrorHandling />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
No comments:
Post a Comment