mongodb-js / charts-embed-sdk

The easiest way to embed MongoDB Charts visualisations into your web app

Home Page:https://docs.mongodb.com/charts/master/embedding-charts-sdk/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

I need to destroy the chart

feyzullahyildiz opened this issue · comments

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>
  )
}

@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);

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.