1

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>
    )
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Does this answer your question? [Where can I make API call with hooks in react?](https://stackoverflow.com/questions/53219113/where-can-i-make-api-call-with-hooks-in-react) – Tushar Shahi Mar 15 '22 at 05:01
  • No, your mentioned question is about how to call API. however, my problem is that API is getting called continuously and it never stops until i refresh the page. Fetching of API should have been stopped after i received the data. – Samriddha Bajpai Mar 15 '22 at 05:03
  • You have to call inside useEffect. Right now it is called every time it is rendered. Don't you wan to call it only once? – Tushar Shahi Mar 15 '22 at 05:04
  • Render -> API Called -> State set -> Rendered -> API called -> State set -> Rendered . Like this. With useEffect you have control, specifically when you want to call code. Read about componendDidMount and componentDidUpdate too (from React class components) – Tushar Shahi Mar 15 '22 at 05:05
  • Thank you for your help too, Will also try to do the same from useEffect. – Samriddha Bajpai Mar 15 '22 at 05:20

1 Answers1

0

You can do the following change in your onChangeHandler() function. It should fix the issue.

The issue was when you were updating the state (setInputValue) in the onChangeHandler() function, the component gets rerender. But inside the if condition you were updating the state again (setDistrictName, setStateName and setDataArray ) which cause some sort of an infinite loop.If you put that if conditon inside the onChangeHandler() function, It will prevent your component from rerendering again and again.

    const onChangeHandler = event => {
        setInputValue(event.target.value);
        if (event.target.value.length === 6) {
          console.log(inputValue)
          axios.get("https://api.postalpincode.in/pincode/" + event.target.value).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);
          })
      }
    };

Full react 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 (event.target.value.length === 6) {
          console.log(inputValue)
          axios.get("https://api.postalpincode.in/pincode/" + event.target.value).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>
    )
}
Ankit Saxena
  • 1,067
  • 1
  • 4
  • 16