Search code examples
javascriptreactjsfirebasegoogle-cloud-firestorereact-map-gl

How to loop through and return the values of a javascript object?


(Apologies if some of my terms aren't correct)

In Firebase I have a number of posts. Each post has a 'latitude' field and a 'longitude' field. I am pulling these out and storing them in an array/object called mapRefs:

useEffect(() => {
    projectFirestore.collection("posts").get().then(res => {
        let mapRefs = [];
        res.forEach(data => {
            mapRefs.push([data.data().myLatitude, data.data().myLongitude]);    
        });
        console.log(mapRefs);

        });
}, []);

This works, the output for the console log is:

0: (2) [-8.6848548, 115.22303799999999]
1: (2) [-8.7848548, 115.323038]
2: (2) [-8.9848548, 115.52303799999999]
3: (2) [-8.8848548, 115.42303799999999]

How do I then iterate through these and map a latitude and longitude value to a component. I was trying like this:

<ReactMapGL>
    { mapRefs && mapRefs.map(coord => (
        <Marker latitude={coord[0]} longitude={coord[1]}>
            <div>
                ...
            </div>
        </Marker>
    ))}
</ReactMapGL>

This isn't working. What would be the correct way to do this, please?


Solution

  • You need use state values to render the UI elements and mapRefs is not available outside useEffect.

    try like this

    const [mapRefs, setMapRefs] = useState([])
    
    useEffect(() => {
        projectFirestore.collection("posts").get().then(res => {
           let refs = [];
           res.forEach(data => {
              refs.push([data.data().myLatitude, data.data().myLongitude]);    
           });
           setMapRefs(refs)
        });
    }, []);
    
    return (
      <ReactMapGL>
        { mapRefs.map(coord => (
            <Marker latitude={coord[0]} longitude={coord[1]}>
                <div>
                    ...
                </div>
            </Marker>
        ))}
    </ReactMapGL>
    )