7 January 2020

Fetch Data in React JS

  • Create Components folder under src folder
  • Add FetchDataExp1.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 FetchDataExp1 extends Component {
constructor(props) {
super(props);
this.state = {
hits: []
};
}
componentDidMount() {
fetch(API + DEFAULT_QUERY)
.then(response => response.json())
.then(data => this.setState({ hits: data.hits }));
}
render() {
return (
<div>
<ul>
{this.state.hits.map(hit => (
<li key={hit.objectID}>
<a href={hit.url}>{hit.title}</a>
</li>
))}
</ul>
</div>
);
}
}
export default FetchDataExp1;
  • Open index.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";

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

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

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

Output:

No comments:

Post a Comment