Home > Net >  Console.log useState causes it to fire multiple times - React Native
Console.log useState causes it to fire multiple times - React Native

Time:09-27

I have the following function. If I try to console.log locationData my console gets overflooded because it logs it multiple times.

function GetGoogleData(){
        const [locationData,setLocationData] = React.useState(undefined);
        let APIURL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${locationID}&key=xxxxxxxxxxxxxxxxxxxxxxxxxxx`;

        let headers = {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
          };
          fetch(APIURL,{
            method: 'POST',
            headers: headers,
          })
          .then((Response)=>Response.json())
          .then((Response)=>{
            setLocationData(JSON.stringify(Response))
            
          });
          console.log(LocationData)
         
    }

CodePudding user response:

Have a try by moving the API call inside the Life Cycle hook useEffect of React.

Ex.

function GetGoogleData(){
    const [locationData,setLocationData] = React.useState(undefined);

    useEffect(() => {
        let APIURL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${locationID}&key=xxxxxxxxxxxxxxxxxxxxxxxxxxx`;

        let headers = {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        };
        fetch(APIURL,{
            method: 'POST',
            headers: headers,
        })
        .then((Response)=> Response.json())
        .then((Response)=>{
            setLocationData(JSON.stringify(Response))
        });
    }, [])

    useEffect(() => {
        if (locationData) {
            console.log('locationData : ', locationData)
        }
    }, [locationData])
}

The first useEffect will only executed first mount of component and the second useEffect will call every update of the locationData State changes.

  • Related