'Having issues with retrieving data when fetching on React

I am having a problem where I am trying to fetch the data from the coordinates stored from the database and display them to the webpage. I am using mapbox as my map display and instead of actual coordinates, it should be the landmark or the nearest location pointed on the map

const [projectCard, setProjectCard] = useState([]);
const geocodeJson = "https://api.mapbox.com/geocoding/v5/mapbox.places/"
const apiKey = "myAPIKey"

useEffect(() => {
    instance.get("/getAvailableProjects").then((response) => {
        setProjectCard(response.data); // <-- retrieve from the database
    });
}, []);

return (
    <div>
        {projectCard.map((val) => {
            let location = ""; // <-- location string stored here

            let coordinate = val.PROJECT_LOCATION;
            const comma = coordinate.indexOf(',');
            const longitude = coordinate.substring(comma + 1);
            const latitude = coordinate.substring(0, comma);
            const url = `${geocodeJson}${longitude},${latitude}.json?${apiKey}`

            const getLocation = () => {
                try {
                    fetch(url).then(response => response.json()).then(data => {

                    location = `${data.features[0].text}, ${data.features[0].context[1].text}, ${data.features[0].context[2].text}, ${data.features[0].context[3].text}`
                    console.log("fetch: " + location) // <-- fetched data displayed at the console as [landmark, city, province]
                    })
                } catch (error) {
                    console.log(error)
                }

                console.log(location) // <-- the output here displayed on the console is empty (this was printed out first on the console)
                return location;
            }

            return(
                <p class="card-text">
                    Location: <br />{getLocation()} 
                </p>
            )
        )}
    </div>
)

I also want to point out that what I have observed when checking at the console is that the "empty" string displays first before the fetched data.

I am still new to using react and I want to know where I went wrong.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source