API Get Request (class-based method)
There are two methods in react js to work on this: class-based and functional components.
HTTP get request using the class-based method:
import React, { Component } from "react";
First, we need to import the above dependencies, which will be used to create a class-based function. There is a shortcut, rce and then press enter key to get the basic structure of the function as follows.
export class Api extends Component {
render() {
return (
<div>Api</div>
)
}
}
export default Api
The only method must be defined in a
React.Component subclass is called render() .constructor(props) {
super(props)
this.state = {
first: ""
}
}
Use rconst snippet for constructors.
The constructor is a method:
The constructor is a method:
- That’s automatically called during the creation of an object from a class.
- It can handle your initial setup stuff like defaulting some properties of the object.
- It can be used to bind event handlers to the component and/or initialize the local state of the component.
- The
constructor()method is fired before the component is mounted. - We take a
propsvalue from theconstructor()and pass it to thesuper()method. - When we call the
super()method, it calls the constructor of the parent class which in the case of a React component isReact.Component.
this.state = {
data: [],
error: ""
}
- The constructor is the only place where you should assign the local state directly like that.
- Any place else in our component, you should rely on
setState()instead.
async getData(){
const url = "https://jsonplaceholder.typicode.com/users";
}
Defining function where we will fetch API URL.
Use trycatch snippet, where we will be adding our code to get data from API URL.
- The
asyncandawaitkeywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
try {
} catch (error) {
}
Use trycatch snippet, where we will be adding our code to get data from API URL.
try {
let response = await fetch(url)
let data = await response.json()
}
Wrap Fetch in a try/catch to handle network errors.
- Fetch will only reject a Promise if there is a network error.
- In the case of 404 or 500, we'll see no errors. That means we must check the response object.
if (!response.ok) {
throw Error(response.statusText);
}
if (data && data.length > 0) {
this.setState({ data: data });
}
Use if condition on data and data length to avoid empty response.
- The
setState()schedule changes to the component’s state object. - It tells React that the component and its children must rerender with the updated state.
catch (error) {
this.setState(error)
}
setState to error to display if the response hits any error.
componentDidMount(){
this.getData();
}
ComponentDidMount function to call getData function.
componentDidMount()which will fire immediately after the component is mounted.- It won’t give us any trouble if we update the state there.
const{data} = this.state
Use destructing in the render component.
- It does not modify an object or array but rather copies the desired items from those data structures into variables.
- These new variables can be accessed later on in a React component.
return (
<div>
{data.map((data) => (data.name))}
</div>
);
Use the map function to map data.
- It is used to traverse and display a list of similar objects of a component.
- It is the standard JavaScript function that could be called on any array.
- It creates a new array by calling a provided function on every element in the calling array.
I have used child components to display data in table form.
return (
<div>
<Headings
element1="id"
element2="name"
element3="email"
element4="city"
element5="zipcode"
/>
{data.map((data) => (
<Rows
element1={data.id}
element2={data.name}
element3={data.email}
element4={data.address.city}
element5={data.address.zipcode}
/>
))}
</div>
);
Row function is as follows:
const Rows = (props) => {
return (
<tr>
<td>{props.element1}</td>
<td>{props.element2}</td>
<td>{props.element3}</td>
<td>{props.element4}</td>
<td>{props.element5}</td>
</tr>
);
};
export default Rows;
Full code:
class Api extends Component {
constructor(props) {
super(props)
this.state = {
data: [],
error: ""
}
}
async getData(){
const url = "https://jsonplaceholder.typicode.com/users";
try {
let response = await fetch(url)
let data = await response.json()
if (data && data.length > 0) {
this.setState({ data: data });
}
}
catch (error) {
this.setState(error)
}
}
componentDidMount(){
this.getData();
}
render() {
const{data} = this.state
return (
<div>
<Headings
element1="id"
element2="name"
element3="email"
element4="city"
element5="zipcode"
/>
{data.map((data) => (
<Rows
element1={data.id}
element2={data.name}
element3={data.email}
element4={data.address.city}
element5={data.address.zipcode}
/>
))}
</div>
);
}
}
export default Api
Wonderful work
ReplyDeleteThanks
DeleteYou solved my problem . Thanks
ReplyDeleteYour welcome
Delete