Widget Not Adding Layers When Configured via JSON in React/Esri App

I’m working on a React component that toggles visibility of map layers in an Esri map. My widget works perfectly when I hardcode the layers configuration, but fails to add layers when I load the configuration from a config.json file.

Working Code Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { React, AllWidgetProps } from 'jimu-core';
import { JimuMapViewComponent, JimuMapView } from 'jimu-arcgis';
import FeatureLayer from 'esri/layers/FeatureLayer';
import { IMConfig } from '../config';
const { useState, useEffect } = React;
const layersConfig = [
{
name: "Layer 1",
url: "https://example.com/arcgis/rest/services/Layer1/MapServer/0",
},
{
name: "Layer 2",
url: "https://example.com/arcgis/rest/services/Layer2/MapServer/0",
}
];
const Widget = (props: AllWidgetProps<IMConfig>) => {
const [jimuMapView, setJimuMapView] = useState<JimuMapView>(null);
const [layers, setLayers] = useState([]); // State initialization moved after handler definition for clarity
console.log('Config on init:', props.config.layers[0].url); // Check initial config
useEffect(() => {
console.log('Config on effect:', props.config); // Check config inside effect
if (props.config && props.config.layers) {
const initialLayers = props.config.layers.map(layerConfig => ({
...layerConfig,
layer: new FeatureLayer({
url: layerConfig.url,
title: layerConfig.name,
visible: false
})
}));
console.log('Initial layers:', initialLayers); // Debug the mapped layers
setLayers([...initialLayers]);
}
}, [props.config]);
const activeViewChangeHandler = (jmv: JimuMapView) => {
if (jmv) {
setJimuMapView(jmv);
console.log('layers:', layers);
layers.forEach(({ layer }) => jmv.view.map.add(layer));
}
};
const toggleLayerVisibility = (index) => {
console.log(`Toggling visibility for layer at index: ${index}`);
const newLayers = layers.map((layer, idx) => {
if (idx === index) {
console.log(`Layer : ${layer.layer}`);
console.log(`Layer before toggle: ${layer.title}, Visible: ${layer.visible}`);
layer.layer.visible = !layer.layer.visible;
console.log(`Layer after toggle: ${layer.title}, Visible: ${layer.visible}`);
}
return layer;
});
setLayers(newLayers);
};
return (
<div className="widget-starter jimu-widget">
{props.useMapWidgetIds && props.useMapWidgetIds.length === 1 && (
<JimuMapViewComponent useMapWidgetId={props.useMapWidgetIds[0]} onActiveViewChange={activeViewChangeHandler} />
)}
<div>
{layers.length > 0 ? layers.map((layer, index) => (
<div key={index}>
<label>
<input
type="checkbox"
checked={layer.layer.visible}
onChange={() => toggleLayerVisibility(index)}
aria-labelledby={`layer-name-${index}`}
/>
<span id={`layer-name-${index}`}>{layer.name}</span>
</label>
</div>
)) : <p>Loading layers...</p>}
</div>
</div>
);
};
export default Widget;
</code>
<code>import { React, AllWidgetProps } from 'jimu-core'; import { JimuMapViewComponent, JimuMapView } from 'jimu-arcgis'; import FeatureLayer from 'esri/layers/FeatureLayer'; import { IMConfig } from '../config'; const { useState, useEffect } = React; const layersConfig = [ { name: "Layer 1", url: "https://example.com/arcgis/rest/services/Layer1/MapServer/0", }, { name: "Layer 2", url: "https://example.com/arcgis/rest/services/Layer2/MapServer/0", } ]; const Widget = (props: AllWidgetProps<IMConfig>) => { const [jimuMapView, setJimuMapView] = useState<JimuMapView>(null); const [layers, setLayers] = useState([]); // State initialization moved after handler definition for clarity console.log('Config on init:', props.config.layers[0].url); // Check initial config useEffect(() => { console.log('Config on effect:', props.config); // Check config inside effect if (props.config && props.config.layers) { const initialLayers = props.config.layers.map(layerConfig => ({ ...layerConfig, layer: new FeatureLayer({ url: layerConfig.url, title: layerConfig.name, visible: false }) })); console.log('Initial layers:', initialLayers); // Debug the mapped layers setLayers([...initialLayers]); } }, [props.config]); const activeViewChangeHandler = (jmv: JimuMapView) => { if (jmv) { setJimuMapView(jmv); console.log('layers:', layers); layers.forEach(({ layer }) => jmv.view.map.add(layer)); } }; const toggleLayerVisibility = (index) => { console.log(`Toggling visibility for layer at index: ${index}`); const newLayers = layers.map((layer, idx) => { if (idx === index) { console.log(`Layer : ${layer.layer}`); console.log(`Layer before toggle: ${layer.title}, Visible: ${layer.visible}`); layer.layer.visible = !layer.layer.visible; console.log(`Layer after toggle: ${layer.title}, Visible: ${layer.visible}`); } return layer; }); setLayers(newLayers); }; return ( <div className="widget-starter jimu-widget"> {props.useMapWidgetIds && props.useMapWidgetIds.length === 1 && ( <JimuMapViewComponent useMapWidgetId={props.useMapWidgetIds[0]} onActiveViewChange={activeViewChangeHandler} /> )} <div> {layers.length > 0 ? layers.map((layer, index) => ( <div key={index}> <label> <input type="checkbox" checked={layer.layer.visible} onChange={() => toggleLayerVisibility(index)} aria-labelledby={`layer-name-${index}`} /> <span id={`layer-name-${index}`}>{layer.name}</span> </label> </div> )) : <p>Loading layers...</p>} </div> </div> ); }; export default Widget; </code>
import { React, AllWidgetProps } from 'jimu-core';
import { JimuMapViewComponent, JimuMapView } from 'jimu-arcgis';
import FeatureLayer from 'esri/layers/FeatureLayer';
import { IMConfig } from '../config';
const { useState, useEffect } = React;

const layersConfig = [
  {
    name: "Layer 1",
    url: "https://example.com/arcgis/rest/services/Layer1/MapServer/0",
  },
  {
    name: "Layer 2",
    url: "https://example.com/arcgis/rest/services/Layer2/MapServer/0",
  }
];

const Widget = (props: AllWidgetProps<IMConfig>) => {
  const [jimuMapView, setJimuMapView] = useState<JimuMapView>(null);
  const [layers, setLayers] = useState([]); // State initialization moved after handler definition for clarity

  console.log('Config on init:', props.config.layers[0].url); // Check initial config

  useEffect(() => {
    console.log('Config on effect:', props.config); // Check config inside effect
    if (props.config && props.config.layers) {
      const initialLayers = props.config.layers.map(layerConfig => ({
        ...layerConfig,
        layer: new FeatureLayer({
          url: layerConfig.url,
          title: layerConfig.name,
          visible: false
        })
      }));
      console.log('Initial layers:', initialLayers); // Debug the mapped layers
      setLayers([...initialLayers]);
    }
  }, [props.config]);

  const activeViewChangeHandler = (jmv: JimuMapView) => {
    if (jmv) {
      setJimuMapView(jmv);
      console.log('layers:', layers);
      layers.forEach(({ layer }) => jmv.view.map.add(layer));
    }
  };

  const toggleLayerVisibility = (index) => {
    console.log(`Toggling visibility for layer at index: ${index}`);
    const newLayers = layers.map((layer, idx) => {
      if (idx === index) {
        console.log(`Layer : ${layer.layer}`);
        console.log(`Layer before toggle: ${layer.title}, Visible: ${layer.visible}`);
        layer.layer.visible = !layer.layer.visible;
        console.log(`Layer after toggle: ${layer.title}, Visible: ${layer.visible}`);
      }
      return layer;
    });
    setLayers(newLayers);
  };

  return (
    <div className="widget-starter jimu-widget">
      {props.useMapWidgetIds && props.useMapWidgetIds.length === 1 && (
        <JimuMapViewComponent useMapWidgetId={props.useMapWidgetIds[0]} onActiveViewChange={activeViewChangeHandler} />
      )}
      <div>
        {layers.length > 0 ? layers.map((layer, index) => (
          <div key={index}>
            <label>
              <input
                type="checkbox"
                checked={layer.layer.visible}
                onChange={() => toggleLayerVisibility(index)}
                aria-labelledby={`layer-name-${index}`}
              />
              <span id={`layer-name-${index}`}>{layer.name}</span>
            </label>
          </div>
        )) : <p>Loading layers...</p>}
      </div>
    </div>
  );
};

export default Widget;

Non-Working Code (using config.json):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Similar to the above, but `layersConfig` is replaced with `props.config.layers`
</code>
<code>// Similar to the above, but `layersConfig` is replaced with `props.config.layers` </code>
// Similar to the above, but `layersConfig` is replaced with `props.config.layers`
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>useEffect(() => {
console.log('Config on effect:', props.config); // Check config inside effect
if (props.config && props.config.layers) {
const initialLayers = props.config.layers.map(layerConfig => ({
...layerConfig,
layer: new FeatureLayer({
url: layerConfig.url,
title: layerConfig.name,
visible: false
})
}));
console.log('Initial layers:', initialLayers); // Debug the mapped layers
setLayers([...initialLayers]);
}
}, [props.config]);
</code>
<code>useEffect(() => { console.log('Config on effect:', props.config); // Check config inside effect if (props.config && props.config.layers) { const initialLayers = props.config.layers.map(layerConfig => ({ ...layerConfig, layer: new FeatureLayer({ url: layerConfig.url, title: layerConfig.name, visible: false }) })); console.log('Initial layers:', initialLayers); // Debug the mapped layers setLayers([...initialLayers]); } }, [props.config]); </code>
useEffect(() => {
    console.log('Config on effect:', props.config); // Check config inside effect
    if (props.config && props.config.layers) {
      const initialLayers = props.config.layers.map(layerConfig => ({
        ...layerConfig,
        layer: new FeatureLayer({
          url: layerConfig.url,
          title: layerConfig.name,
          visible: false
        })
      }));
      console.log('Initial layers:', initialLayers); // Debug the mapped layers
      setLayers([...initialLayers]);
    }
  }, [props.config]);

config.json:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"layers": [
{
"name": "Layer 1",
"url": "hidden",
},
{
"name": "Layer 2",
"url": "hidden"
}
]
}
</code>
<code>{ "layers": [ { "name": "Layer 1", "url": "hidden", }, { "name": "Layer 2", "url": "hidden" } ] } </code>
{
  "layers": [
    {
      "name": "Layer 1",
      "url": "hidden",
    },
    {
      "name": "Layer 2",
      "url": "hidden"
    }
  ]
}

config.ts:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { ImmutableObject } from 'seamless-immutable';
export interface LayerConfig {
name: string;
url: string;
}
export interface Config {
layers: LayerConfig[];
}
export type IMConfig = ImmutableObject<Config>;
</code>
<code>import { ImmutableObject } from 'seamless-immutable'; export interface LayerConfig { name: string; url: string; } export interface Config { layers: LayerConfig[]; } export type IMConfig = ImmutableObject<Config>; </code>
import { ImmutableObject } from 'seamless-immutable';

export interface LayerConfig {
  name: string;
  url: string;
}

export interface Config {
  layers: LayerConfig[];
}

export type IMConfig = ImmutableObject<Config>;

Error Message:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>TypeError: Cannot read properties of undefined (reading 'add')
</code>
<code>TypeError: Cannot read properties of undefined (reading 'add') </code>
TypeError: Cannot read properties of undefined (reading 'add')

This error occurs at the line where I try to add layers to the map:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>layers.forEach(({ layer }) => jmv.view.map.add(layer));
</code>
<code>layers.forEach(({ layer }) => jmv.view.map.add(layer)); </code>
layers.forEach(({ layer }) => jmv.view.map.add(layer));

Extra:

Here is initial layers for the working sample:
enter image description here
And for the non-working:
enter image description here

  1. Checked the URLs in the config file to ensure they are correct and accessible.
  2. Added logs to various points in the component to ensure the data is being loaded and state changes are occurring as expected.
  3. Ensured the component is correctly re-rendering on state changes.

Please help I’ve been trying to figure it out by different means for the past 10 hours…

New contributor

DaviHlav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật