ShaneOG97
ShaneOG97

Reputation: 530

ReactJs issues with setstate on array in ChartJs

Very weird issue I am having working with react-chart-js 2, I have two fiddles to clearly demonstrate this problem. Basically I am using axios to pull API data to create my charts, when I click on a table header (the name or number header) to sort the data, the chart column data messes up and fails to work properly. However If I use basic dummy data on the componentDidMount function such as [1,2,3,4] then the sorting of the charts works exactly as expected. Why is this happening.

Fiddle 1 (with correct componentDidMount data and sorting causing issues)

https://codesandbox.io/s/confident-tdd-bj0sr

Fiddle 2 (dummy data and sorting works as expected

https://codesandbox.io/s/laughing-williams-in5ei

Upvotes: 1

Views: 170

Answers (1)

tbauer428
tbauer428

Reputation: 73

I believe the issue is how you are keying your element in your render() method.

You have:

  {this.state.data.map((n, index) => {
          return (
            <tr key={index}>
              <td component="th" scope="row">
                {n.market_cap_rank}
              </td>
              <td> {n.name} </td>

I played around with your JSFiddle and found that keying it out to the data elements id (n.id) causes the filters to behave as expected.

I changed it like below (notice the key on the first element):

{this.state.data.map((n, index) => {
          return (
            <tr key={n.id}>
              <td component="th" scope="row">
                {n.market_cap_rank}
              </td>
              <td> {n.name} </td>

Here is a link to my fork of your JSFiddle https://codesandbox.io/s/intelligent-violet-6ixcm

Bear in mind that this does not retain that admittedly very slick transition on the line graphs, but this should hopefully point you in a good direction.

Upvotes: 1

Related Questions