Search code examples
reactjsreact-leaflet

React-Leaflet can't input marker position from fetching API


I try to input a marker position by fetching an API into the map but doesn't work.

Here is my component's code.

import React, { useState, useEffect } from 'react';
import { MapContainer, TileLayer, Marker } from 'react-leaflet'

const Map = () => {

    const [parcels, setParcels] = useState([])
    const center = [14.881999606787934, 102.02071765448805]

    useEffect(async () => {
        try {
            const res = await fetch('http://localhost:3000/api/parcels/all')
            const getParcels = await res.json()
            setParcels(getParcels)
        } catch (e) {
            setParcels(e)
        }
    }, [])

    const position = parcels.map((parcel) => {
        return [parcel.location.coordinates[1], parcel.location.coordinates[0]]
    })

    return (
        <div>
            <MapContainer center={center} zoom={15} scrollWheelZoom={false} className="h-screen">
                <TileLayer
                    attribution='&copy; Taxmap'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={position[0]}></Marker>
            </MapContainer>
        </div>
    )
}

export default Map

Error message from the console. enter image description here

If I use console.log() to see the position[0]. It looks like normally.

console.log(position[0])
// result = [14.8763983, 102.0169941]

enter image description here

But when I create a variable normally. It can work.

const positionButArray = [14.8763983, 102.0169941]

return (
        <div>
            <MapContainer center={center} zoom={15} scrollWheelZoom={false} className="h-screen">
                <TileLayer
                    attribution='&copy; Taxmap'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={positionButArray}></Marker>
            </MapContainer>
        </div>
      )

The result from above. enter image description here

If anyone has a solution please help me. Thanks


Solution

  • I have solved the problem by just adding a ternary operator to check if a position is rendered or not. If the position is rendered, It's going to return the Marker tag. here is my solution.

    return (
            <MapContainer center={center} zoom={15} scrollWheelZoom={false} className="h-screen">
                <TileLayer
                    attribution='&copy; Taxmap'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                {positions? <Marker position={positions[0]}></Marker>:null}
            </MapContainer>
        )