I want to display data from API on the chart and I know how to do it but I have error while using .map function. I want to separate prices[0]from prices [1] to have access to two of them because my response looks like this:
"prices": [
[
1689598842536,
30208.47
],
[
1689602431443,
30274.72
],
Here is the code with .map function:
const params = useParams()
const [coin, setCoin] = useState({})
const [chart, setChart] = useState({})
const [loading, setLoading] = useState(false)
const chartUrl = `https://api.coingecko.com/api/v3/coins/${params.coinId}/market_chart?vs_currency=usd&days=30&precision=2`
const url = `https://api.coingecko.com/api/v3/coins/${params.coinId}`
useEffect(() => {
axios.get(url).then((res) => {
setCoin(res.data)
setLoading(true)
}).catch((error) => {
console.log(error)
})
axios.get(chartUrl).then((res) => {
setChart(res)
}).catch((error) => {
console.log(error)
})
}, [])
const coinChartData = chart.prices.map(value => ({x: value[0], y: value[1]}))
I have got error in last line:
Cannot read properties of undefined (reading 'map')
I tried put coinChartData inside useEffect and it worked but I couldn't use coinChartData outside useEffect function.
The initial value for
chartis an empty object:That object has no
pricesproperty so, just as the error states,chart.pricesisundefined.You could perhaps initialize such a property to an empty array:
Or you could use optional chaining when accessing a potentially
undefinedproperty:You may have other options as well, depending on where/how you eventually use this data. But any way you look at it, if the object might not have the
pricesproperty then you can't always use that property. You'd need to either ensure the property always exists or in some way conditionally check if it exists before trying to use it.