React .map not working when trying to set data for display on chart
P粉277464743
P粉277464743 2023-08-17 11:56:29
0
1
540
<p>I want to display data from the API on a chart, I know how to do it, but I get an error when using the .map function. I want to separate prices[0] and prices[1] so I can access them since my response looks like this: </p> <pre class="brush:php;toolbar:false;">"prices": [ [ 1689598842536, 30208.47 ], [ 1689602431443, 30274.72 ],</pre> <p>This is the code with the .map function: </p> <pre class="brush:php;toolbar:false;">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]}))</pre> <p>I get the error on the last line <code>Cannot read properties of undefined (reading 'map')</code></p> <p>I tried putting coinChartData inside useEffect and it works, but I can't use coinChartData outside useEffect function. </p>
P粉277464743
P粉277464743

reply all(1)
P粉133321839

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template