0

I'm using an API for fetching data and it works just fine, by the way I'm using redux. when I refresh my project. I get this error. I also Have et loading so when data is not fetched, waits for it. I have no clue what to do.

This is the component which I used data in

import React, { useEffect } from 'react';
import { useSelector, useDispatch} from 'react-redux';
import { Link } from 'react-router-dom';
import millify from 'millify';

//Redux
import { fetchCoins } from "../../redux/coins/coinsAction";

const Homepage = () => {

   const dispatch = useDispatch();
   const {coins, loading } = useSelector(state => state.coinsState);

   useEffect(() => {
      dispatch(fetchCoins());
   }, [])
   console.log(coins);


   return (
    <>
        {
            loading ? <h1>Loading...</h1> :
            <div>
                <h2>Global Crypto Stats</h2>
                <div>
                    <h5>Total Cryptcurrencies</h5>
                    <span>{millify(coins.data.stats.total)}</span>
                    <h5>Total Exchanges</h5>
                    <span>{millify(coins.data.stats.totalExchanges)}</span>
                    <h5>Total Market cap</h5>
                    <span>{millify(coins.data.stats.totalMarketCap)}</span>
                    <h5>Total 24h Volume</h5>
                    <span>{millify(coins.data.stats.total24hVolume)}</span>
                    <h5>Total Markets</h5>
                    <span>{millify(coins.data.stats.totalMarkets)}</span>
                </div>
            </div>
        }
        
    </>
   );
};

export default Homepage;
JustAG33K
  • 1,403
  • 3
  • 13
  • 28
Milad.eb96
  • 40
  • 4
  • The error message says, `coins.data` is `undefined`, & you are trying to read `stats` of the value `undefined` which doesn't have any meaning. Make sure `coins.data` is not undefined and its an object – Dilshan Aug 24 '22 at 14:20
  • This suggests that `coins.data` is `undefined`. What information do you have which suggests otherwise? When this happens, what is the value of `coins`? What do you expect it to be? Why? – David Aug 24 '22 at 14:21
  • Try using optional chaining on the properties that you are trying to access. – Abdullah Ansari Aug 24 '22 at 14:21

1 Answers1

1

When facing this issue, the main solution is to put "?" before each dots, it should look like this :

coins?.data?.stats?.total

Try this :)

Le D
  • 115
  • 7