React .map doesn't work while trying to set data for displaying on the chart

31 Views Asked by At

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.

1

There are 1 best solutions below

0
David On

The initial value for chart is an empty object:

const [chart, setChart] = useState({})

That object has no prices property so, just as the error states, chart.prices is undefined.

You could perhaps initialize such a property to an empty array:

const [chart, setChart] = useState({ prices: [] })

Or you could use optional chaining when accessing a potentially undefined property:

const coinChartData = chart.prices?.map(value => ({x: value[0], y: value[1]}))

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 prices property 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.