Search code examples
react-nativeapiaxiosgetcoingecko

undefined is not an object when using axios


I am using the code below to get data from the CoinGecko API and then set states to the data returned however when I console.log for example general.data, 'undefined' is being logged. Can someone point out how the code is to be modified such that it functions as required?

  const [currentChartData, setChart] = useState();
  const [currentIndicator, setIndicator] = useState();
  const [bitcoinGeneral, setGeneral] = useState();
  const [yearData, setYearData] = useState();
  const [monthData, setMonthData] = useState();
  const [dayData, setDayData] = useState();

  useEffect(() => {
    const fetchData = async () => {
      const general = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=true')
      if(general.data)
      setGeneral(general.data);

      const year = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=365&interval=daily')
      if(year.data)
      setYearData(year.data);

      const month = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=30&interval=daily')
      if(month.data)
      setMonthData(month.data);

      const day = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=1&interval=hourly')
      if(day.data)
      setDayData(day.data);
    }
    fetchData()
  }, [])

enter image description here


Solution

  • Your component is rendered once before useEffect() is called. During that run, bitcoinGeneral value is undefined. Hence you are seeing that error.

    To fix it, use optional chaining operator ?. while accessing that state.

    <Text>{bitcoinGeneral?.symbol.toUpperCase()}</Text>
    

    You have to do this in all places where bitcoinGeneral is accessed.

    Another option is to do conditional rendering. Example -

    if (!bitcoinGeneral) {
      return null; // or something else
    }
    
    return (
      <View>
        <Text>{bitcoinGeneral.symbol.toUpperCase()}</Text>
      </View>
    )