# Error on datasource remove

**URL:** <https://community.cesium.com/t/error-on-datasource-remove/24447>\
**Category:** CesiumJS\
**Created:** [May 31, 2023, 4:01pm UTC](https://community.cesium.com/t/error-on-datasource-remove/24447 "2023-05-31T16:01:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dum](https://sea2.discourse-cdn.com/cesium/user_avatar/community.cesium.com/dum/32/13981_2.png) [@dum](https://community.cesium.com/u/dum)\
**Post date:** [May 31, 2023, 4:01pm UTC](https://community.cesium.com/t/error-on-datasource-remove/24447/1 "2023-05-31T16:01:17Z")

</div>

I a using **Cesium 1.105.0** with **React 18 on StrictMode.**  
I am adding a datasource to viewer datasources, then removing it on component unmount. When removing it I have this error:

```auto
An error occurred while rendering. Rendering has stopped.
TypeError: Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
    at DataSourceDisplay.update (http://localhost:6006/node_modules/.vite-storybook/deps/cesium.js?v=1c1f44d1:153412:27)
    at Viewer._onTick (http://localhost:6006/node_modules/.vite-storybook/deps/cesium.js?v=1c1f44d1:250246:45)
    at Event.raiseEvent (http://localhost:6006/node_modules/.vite-storybook/deps/cesium.js?v=1c1f44d1:23095:20)
    at Clock.tick (http://localhost:6006/node_modules/.vite-storybook/deps/cesium.js?v=1c1f44d1:130830:15)
    at CesiumWidget.render (http://localhost:6006/node_modules/.vite-storybook/deps/cesium.js?v=1c1f44d1:214044:37)
    at render2 (http://localhost:6006/node_modules/.vite-storybook/deps/cesium.js?v=1c1f44d1:213460:18)

```

Here is my code:

```auto
/**
 * Context allowing to use a cesium datasource
 */
function DataSourceProvider({ children, collectionName }: { children: ReactNode; collectionName: string; }) {
  const { viewer } = useCesiumViewer();
  const dataSource = useRef<CustomDataSource>(new CustomDataSource(collectionName));

  // Initialize collection
  useEffect(() => {
    if (!viewer.dataSources.contains(dataSource.current)) {
      viewer.dataSources.add(dataSource.current);
    }

    // Delete collection on component unmount
    return () => {
      if (!viewer.dataSources.isDestroyed() && viewer.dataSources.contains(dataSource.current)) {
        viewer.dataSources.remove(dataSource.current, true);
        viewer.scene.requestRender();
      }
    };
  }, [viewer]);

  return <DataSourceContext.Provider value={dataSource.current}>{children}</DataSourceContext.Provider>;
}

```

I could use `datasource.current.entities.removeAll()` but the viewer datasources list would keep useless datasources after emptying them.  
Even returning `null` instead of DataSourceContext object, the error still produce on component unmount.

So this error comes from the viewer.datasources.remove function, would you know how to prevent this from happening?

Thank you for your help!
