Problem Statement:- i wanted to have a respective post-office dropdown for the user entered pincode. In this way, i have used below mentioned api to call with axios. I got the required post office details in the dropdown but the problem is that the fetching of data never stops, i keep getting the extracted data from API continuously and it never stops until I close the server. Below is my mentioned code.
import React, { useState } from 'react'
import axios from "axios"
export default function Test() {
const [inputValue, setInputValue] = React.useState("");
const [districtName, setDistrictName] = React.useState("");
const [stateName, setStateName] = React.useState("");
const [dataArray, setDataArray] = React.useState("")
const onChangeHandler = event => {
setInputValue(event.target.value);
};
if (inputValue.length === 6) {
console.log(inputValue)
axios.get("https://api.postalpincode.in/pincode/" + inputValue).then(res => {
var data = res.data;
console.log("data: ", JSON.stringify(data))
setDistrictName(data[0].PostOffice[0].District)
setStateName(data[0].PostOffice[0].State)
console.log("data_1: ", districtName + " " + stateName)
var items = []
data[0].PostOffice.forEach(element => {
items.push(<option value={element.Name}>{element.Name}</option>)
});
setDataArray(items);
console.log("items:",items);
})
}
return (
<div>
<div>
<label type="text" name="pincode">Pincode</label>
<input
type="text"
name="pincode"
onChange={onChangeHandler}
value={inputValue}
/>
</div>
<div>
<label type="text" name="district">District</label>
<input
type="text"
name="district"
value={districtName}
/>
</div>
<div>
<label type="text" name="state">State</label>
<input
type="text"
name="state"
value={stateName}
/>
</div>
<select>
{dataArray}
</select>
</div>
)
}