Why can't I update my data in lightweight charts?

Viewed 20

This is my initial data

var array = [
      {
        time: "2022-04-18",
        open: Number(`${125.05}`),
        high: Number(`${127.05}`),
        low: Number(`${123.05}`),
        close: Number(`${126.05}`),
      },
    ];

When I try to update the charts with the same data format like this:

updated.unshift({
            time: `${key}`,
            open: Number(`${val[["1. open"]]}`),
            high: Number(`${val[["2. high"]]}`),
            low: Number(`${val[["4. close"]]}`),
            close: Number(`${val[["4. close"]]}`),
          });

it gives me an error
lightweight-charts.esm.production.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'year')

1 Answers

After you've set your data for the series using setData, you can use update to add new data to the series. Please note that this method can only take a single data point at a time and the time must either match the last data point of the series or be a later date.

If you are using unshift then you are adding data to the start of the array. If you are modifying the array yourself then you need to use the setData method again with the array as the parameter. This will replace all the data for that series with the new data. This isn't as performant as the updateData method but if you are wanting to add to the start of the array then this is the approach you will need to use.

array = [
      {
        time: "2022-04-18",
        open: 125.05,
        high: 127.05,
        low: 123.05,
        close: 126.05,
      },
      // ... more data
    ];
series.setData(array);

// ...

// adding new data point to end of data
series.update({
  time: "2022-04-19",
  open: 123.4,
  close: 123.4,
  high: 123.4,
  low: 123.4,
});

// If you need to add to the start then you will need to use setData
array.unshift({
  time: "2022-04-19",
  open: 123.4,
  close: 123.4,
  high: 123.4,
  low: 123.4,
});
series.setData(array); // Not recommended in most use cases.
Related