Error state not defined in React

Hi,
I was trying the whole week to fix this App in the lesson of usestate but it’s not working, I give up.
I did the same as zsolt did, I’m seeing an error state not defined even if I imported usestate.

import React, {useState} from 'react';
import CoinList from './components/CoinList/CoinList';
import AccountBalance from './components/AccountBalance/AccountBalance';
import ExchangeHeader from './components/ExchangeHeader/ExchangeHeader';
import styled from 'styled-components';
import axios from 'axios';

const Div = styled.div`
  text-align: center;
  background-color: rgb(44, 44, 182);
  color: #cccccc;
`;

const COIN_COUNT = 10;
const formatPrice = price => parseFloat(Number(price).toFixed(4));
function App(props) {
  const [balance, setBalance] = useState(10000);
  const [showBalance, setShowBalance] = useState(true);
  const [coinData, setCoinData] =useState([]);

  const componentDidMount = async () => {
    const response = await axios.get('https://api.coinpaprika.com/v1/coins');
    const coinIds = response.data.slice(0, COIN_COUNT).map(coin => coin.id);
    const tickerUrl = 'https://api.coinpaprika.com/v1/tickers/';
    const promises = coinIds.map(id => axios.get(tickerUrl + id));
    const coinData = await Promise.all(promises);
    const coinPriceData = coinData.map(function(response) {    
      const coin = response.data;
      return {
        key: coin.id,
        name: coin.name,
        ticker: coin.symbol,
        balance: 0,
        price: parseFloat(Number(coin.quotes.USD.price).toFixed(4)),
    };
  });
      setCoinData(coinPriceData);
  }
  const handleBalanceVisibilityChange = () => {
    setShowBalance(oldValue => !oldValue);
  }
     /*useEffect(function() {
      if (coinData.length === 0 ) {
        componentDidMount();
    } 
  });*/
 
 
  const handleRefresh = async (valueChangeId) => {
    const tickerUrl = `https://api.coinpaprika.com/v1/tickers/${valueChangeId}`;
    const response = await axios.get(tickerUrl);
    const newPrice = formatPrice(response.data.quotes.USD.price);
    const newCoinData = coinData.map( function( values ) {
      let newValues = { ...values };
      if ( valueChangeId === values.key) {
        newValues.price = newPrice;
      }
      return newValues; 
    });    

    setCoinData(newCoinData);
  }

  return (
    <Div className="App">
        <ExchangeHeader />
        <AccountBalance 
        amount={state.balance} 
        showBalance={state.showBalance} 
        handleBalanceVisibilityChange={handleBalanceVisibilityChange} />
        <CoinList 
        coinData={state.coinData} 
        showBalance={state.showBalance}
        handleRefresh={handleRefresh} />
    </Div>
    );
}
export default App;

1 Like

this.state.balance ?
this.state.showBalance ?
this.state.coinData ?

 <AccountBalance 
        amount={state.balance} 
        showBalance={state.showBalance} 
        handleBalanceVisibilityChange={handleBalanceVisibilityChange} />
        <CoinList 
        coinData={state.coinData} 
        showBalance={state.showBalance}
        handleRefresh={handleRefresh} />

I am not sure about this, because in my code I found that we used functional components and therefore my code looks like this:

App.js
import React, {useState, useEffect} from 'react';
// import { v4 as uuidv4 } from 'uuid';

import Coinlist from './components/Coinlist/Coinlist';
import AccountsBalance from './components/AccountsBalance/AccountsBalance';
import ExchangeHeader from './components/ExchangeHeader/ExchangeHeader';

import styled from 'styled-components';
import axios from 'axios';

const Div = styled.div`
text-align: center;
background-color: rgba(11, 11, 114, 0.938);
color: #cccccc
`;

const coinCount = 9;
const formatPrice = price => parseFloat(Number(price).toFixed(4));

function App(props) {
  const [balance, setBalance] = useState(10000);
  const [showBalance, setShowBalance] = useState(true);
  const [coinData, setCoinData] = useState([]);

  const componentDidMount = async () => {
  const response = await axios.get('https://api.coinpaprika.com/v1/coins');

  const coinIds = response.data.slice(0, coinCount).map(coin => coin.id); 
  const tickerURL = 'https://api.coinpaprika.com/v1/tickers/';
  const promises = coinIds.map((id) => axios.get(tickerURL + id));
  const coinData = await Promise.all(promises);
  const coinPriceData = coinData.map(function(response) {
    const coin = response.data;
    return {
      key: coin.id,
      name: coin.name,
      ticker: coin.symbol,
      balance: 0,
      price: formatPrice(coin.quotes.USD.price),
    }
  })
  //Retrieve prices here
  setCoinData(coinPriceData);
  }

  
 useEffect(function() {

  if(coinData.length === 0){
    componentDidMount();
  }
});


  const handleShowHide = () => {
    setShowBalance(oldValue => !oldValue);
   }
   

  const handleRefresh = async (valueChangeId) => {
    const tickerURL = `https://api.coinpaprika.com/v1/tickers/${valueChangeId}` ;
    const response = await axios.get(tickerURL);
    debugger;
    const newPrice = formatPrice(response.data.quotes.USD.price);
    const newCoinData = coinData.map(function ( values ) {  //input argument is 1 object {} with a ticker, name and price
      let newValues = { ...values };
    if(valueChangeId === newValues.key) {
      newValues.price = newPrice;
    }
      return newValues;
    });
    
   
    setCoinData(newCoinData);
  }
    return (
      <Div>
        <ExchangeHeader />
        <h2><AccountsBalance amount={balance} 
                             showBalance={showBalance}
                             handleShowHide={handleShowHide} 
            />
        </h2>
        <Coinlist coinData = {coinData} 
                  showBalance={showBalance}
                  handleRefresh={handleRefresh} 
        />
      </Div>
    );
 
}

export default App;

Feel free to check out my repo here and compare it to your code.

1 Like

I took off all “this.” I did exactly like the teacher, I was wondering how come everything was ok from the modifications of the lesson Usestate hook, nothing is working.

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Section = styled.section`
        font-size: 2rem;
        text-align: left;
        padding: 1.5rem 0 1.5rem 5rem;
`;

export default function AccountBalance (props) {
   
    const buttonText = props.showBalance ? 'Hide Balance' : 'Show Balance';
    let content = null;
    if ( props.showBalance ) {
        content = <>Balance: ${props.amount}</>;
    }
    return (
        <Section>
            {content}
            <button onClick={props.handleBalanceVisibilityChange}>{buttonText}</button>
        </Section>
    );
   
}

AccountBalance.propTypes = {
    amount: PropTypes.number.isRequired
}