0
votes

I've got problem about how export nested const 'mapObj' in below example, because i need this in another component to get some information from this object. When I want to export nested const then I've got error that you can export only on the top.

First component:

const Mapper = ({
                    componentId,
                    width,
                    height,
                    xRenderCoord,
                    yRenderCoord,
                    zoom,
                    projection,
                    markerLayers = new TileLayer({
                        source: new OSM()
                    })
                }) => {
    const initMap = () => {
      const mapObj = new Map({
            controls: controls,
            target: componentId === '' ? 'map' : componentId,
            layers: [
                new TileLayer({
                    source: new OSM()
                }),
                markerLayers
            ],
            view: new View({
                projection: projection,
                center: fromLonLat([xRenderCoord, yRenderCoord]),
                zoom: zoom
            })
        })
    }

    useEffect(() => {
        initMap()
    }, [])

    return (
        <React.Fragment>
            <div
                id={componentId === '' ? 'map' : componentId}
                style={{
                    width: width,
                    height: height
                }}
            />
        </React.Fragment>
    )
}

export default Mapper

second component:

const MapService = (props) => {

async function vectorLoader(data) {
        var geoJsonFormat = new GeoJSON();
        var features = geoJsonFormat.readFeatures(data, {
            featureProjection: mapObj.getView().getProjection()
        })
    }

 return (
        <>
            <Mapper
                componentId='map'
                width='800px'
                height='800px'
                xRenderCoord={19}
                yRenderCoord={52}
                zoom={6}
                projection='EPSG:3857'
                
            />
        </>
    )
}

Do you have any idea to solve this problem?

1

1 Answers

0
votes

You can't export something that isn't defined at the top level of a module. In your case, mapObj is defined within the initMap function, which means that A) It may never exist at all (if the function is never called), which makes it hard to export. :-) And B) Multiple mapObjs may exist (one for each time initMap is called.)

So if you want to export it, you'll have to do that by defining it at the top level of the module, if feasible. It doesn't immediately look like it's feasible, given that it appears to depend on the values of parameters to the Mapper function (and some controls variable that isn't declared in the code shown).