P粉1333218392023-08-18 00:07:47
The initial value of chart
is an empty object:
const [chart, setChart] = useState({})
The object does not have a prices
property, so as the error states, chart.prices
is undefined
.
You can initialize this property to an empty array:
const [chart, setChart] = useState({ prices: [] })
Or use optional chaining when accessing properties that may be undefined
:
const coinChartData = chart.prices?.map(value => ({x: value[0], y: value[1]}))
Depending on where/how you end up using the data, you may have other options. But anyway, if the object may not have a prices
property, then you can't always use that property. You need to make sure the property is always present, or somehow conditionally check if it exists before trying to use it.