Starter-code
Starter-code

Reputation: 1

SPFX-Chart-webpart-react-pnpcontrol

I am having a spfx webpart where it shows a chart view based on the List selected in property pane. I can able to generate the chart but while changing the list the second chart data shows the prev chart data on hover.The below code is on render method in .tsx file

<ChartControl                  
        type={ChartType.Bar}                   
         data promise={this._data()}                      
         options={{
         legend: {
         display: true,
         position: "right",                
         },
         title: {
         display: true,
         text: "My Chart Data"
         },  
         }} />

The _data() method will be as below,

let Chart:Chart;
Chart.ChartData = {
    labels: ['Income','Expense','Debt','Savings'],
    datasets: [{
      label: 'Archive',
      data: [10,13,20,90]          
    }]
  };

I have tried to implement,

Chart.destroy()/Chart.clear()

but not working.It shows error and get rejected saying the Chart is un definded.

How to clear the old data,while loading next list in this scenario.

Upvotes: 0

Views: 1127

Answers (3)

user2343766
user2343766

Reputation: 11

Use below code.

public refchart:any; 

public constructor(props: any) {
 this.refchart = React.createRef();
}

//render function

Before you set value in state write below code

if(this.refchart){
  this.refchart.current.props.data?.datasets.pop();
  this.refchart.current._destroyChart();
}

then set state

this.setState({chartData:yourstatedata});

Upvotes: 0

Starter-code
Starter-code

Reputation: 1

Chart.datasets.pop();

Using this line in the code will empty the datasets, hence the new data will be added and hovering the chart will not show old data.

Upvotes: 0

Amos
Amos

Reputation: 2091

@Starter-code

 this.state = {
          data: {
            labels:
              [
                'January', 'February', 'March', 'April', 'May', 'June', 'July'
              ],
            datasets:
              [{
                label: 'My Second Dataset',
                data:
                  [
                    65, 59, 80, 81, 56, 55, 40
                  ]
              }]
          }
        };

Upvotes: 0

Related Questions