7 January 2020

Fetch Data with Loading option in React JS

  • Create Components folder under src folder
  • Add FetchDataLoading.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 FetchDataLoading extends Component {
constructor(props) {
super(props);
this.state = {
hits: [],
isLoading: false
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch(API + DEFAULT_QUERY)
.then(response => response.json())
.then(data => this.setState({ hits: data.hits, isLoading: false }));
}
render() {
const { hits, isLoading } = this.state;
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 FetchDataLoading;
  • Open index.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import FetchDataLoading from "./Components/FetchDataLoading";

function App() {
return (
<div className="App">
<FetchDataLoading />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:


No comments:

Post a Comment