mongodb-js / charts-embed-sdk

The easiest way to embed MongoDB Charts visualisations into your web app
https://docs.mongodb.com/charts/master/embedding-charts-sdk/
Apache License 2.0
43 stars 31 forks source link

I need to destroy the chart #74

Closed feyzullahyildiz closed 10 months ago

feyzullahyildiz commented 1 year ago

Describe the bug destroyChart and destroyDashboard functions does not exists. How can I destroy these charts.


import React, { useLayoutEffect, useRef} from 'react';
import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
export const App() {
  const divRef = useRef(document.createElement('div'));

  useLayoutEffect(() => {
    const sdk = new ChartsEmbedSDK({
      baseUrl: 'https://charts.mongodb.com/charts-chartsss-ktjra',
    });
    const chart = sdk.createChart({
      chartId: '137cc4ba-09cb-413e-2226-9e119ff05343',
      getUserToken: () => window.prompt('Type your token') || ''
    });
    chart.render(divRef.current);
    return () => {

      // I need to destroy the chart over here

    }

  }, [])
  return (
    <div className='chart' ref={divRef}></div>
  )
}
matt-d-rat commented 1 year ago

@feyzullahyildiz Thank you for raising this issue. I agree that the SDK should expose some sort of destroy method to assist with cleaning up the DOM nodes created inside the divRef element, we will look into adding this functionality to the SDK.

In the interim I have put together this CodeSandbox example for you, to demonstrate how to manually do this cleanup yourself inside the function returned by useLayoutEffect.


I also noticed a small error in your usage of useRef in the example code provided. You should not be manipulating the DOM directly by creating an element as the initial value to useRef like you are below:

const divRef = useRef(document.createElement('div'));

All this is doing is creating an Element which is not being used by the document, as the reference is later assigned the <div className='chart' /> node. Instead, divRef should be initialised as null:

const divRef = useRef(null);
kristinamongo commented 10 months ago

Closing this as it's a feature request rather than a bug. Thank you @matt-d-rat for providing a workaround. I've posted the idea to the MDB Charts Feature Request page to get more visibility and upvotes - you can find it here.