Async function not working inside UseEffect Hook Code Answer

I am creating an async function inside the useEffect callback. But because of some reason, every time component renders, I can only see the output from the first console. And execution control never goes inside the async function. Thus returning empty array at the end.

const [targets, setTargets] = useState([]);
useEffect(() => {
    console.log("Inside UseEffect"); //logs the output
    (async () => {
        var url = `https://xx.yy.zz/?param={"request_type":"query_osm_circle","lat":${region.latitude},"lng":${region.longitude},"radius":3,"limit":10}`;
        try {
            let response = await fetch(
                url,
            );
            let responseJson = await response.json();
            console.log(responseJson); //does not log the output
            setTargets(responseJson);
        } catch (error) {
            console.error(error);
        }
    })
});
console.log(targets); //returns empty array

Answer

 useEffect(() => {
     console.log("Inside UseEffect"); //logs the output
     (async () => {
         var url = `https://xx.yy.zz/?param={"request_type":"query_osm_circle","lat":${region.latitude},"lng":${region.longitude},"radius":3,"limit":10}`;
         try {
             let response = await fetch(
                 url,
             );
             let responseJson = await response.json();
             console.log(responseJson); //does not log the output
             setTargets(responseJson);
         } catch (error) {
             console.error(error);
         }
     })()
 },[]);

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji