Coding exercise - 5 coins

https://codepen.io/EmmerichS/pen/mdOpxQz

I enjoyed this task. Good learning curve.

2 Likes

This one took me far longer to understand than I felt it should have lol. But here it is!

2 Likes

2 Likes

See the Pen eYBPOWm by Bozidar (@Zibodar)

2 Likes

Guys! My Brain is Buzzing! This whole project is far above my level, but I am amazed to go through all of this and will surely review it a couple of times.

import React, { Component } 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;

class App extends React.Component {
  state = {
    balance: 10000,
    showBalance: true,
    coinData: [ /*
      {
        key: uuidv4(),
        name: "Bitcoin",
        ticker: "BTC",
        balance: 1,
        price: 9999.99
      },
      {
        key: uuidv4(),
        name: "Ethereum",
        ticker: "ETH",
        balance: 32,
        price: 1800.25
      },
      {
        key: uuidv4(),
        name: "Tether",
        ticker: "USDT",
        balance: 0,
        price: 1.0
      },
      {
        key: uuidv4(),
        name: "Ripple",
        ticker: "XRP",
        balance: 1000,
        price: 0.98
      },
      {
        key: uuidv4(),
        name: "Bitcoin Cash",
        ticker: "BCH",
        balance: 0,
        price: 435.45
      } */
    ]
  }
  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: parseFloat(Number(coin.quotes.USD.price).toFixed(4)),
    }
  })
  //Retrieve prices here
  this.setState({ coinData: coinPriceData });
  }


  handleShowHide = () => {
    this.setState(function (oldState) {
     return {
       ...oldState,
       showBalance: !oldState.showBalance
     }
    });
   }

  handleRefresh = (valueChangeTicker) => {
    const newCoinData = this.state.coinData.map(function ( values ) {  //input argument is 1 object {} with a ticker, name and price
      let newValues = { ...values };
    if(valueChangeTicker === newValues.ticker) {
      const randomPercentage = 0.995 + Math.random() * 0.01;
      newValues.price *= randomPercentage;
          
    }
      return newValues;
    });
    
    //  SetStatefunction could look like this too: this.setState( oldState => {/*inputnewstatehere*/})
    //but this is also possible, if we use a part of a state only
    this.setState({coinData: newCoinData}); //also works with an object {}
  }
 

  render(){

    return (
      <Div>
        <ExchangeHeader />
        <h2><AccountsBalance amount={this.state.balance} 
                             showBalance={this.state.showBalance}
                             handleShowHide={this.handleShowHide} 
            />
        </h2>
        <Coinlist coinData = {this.state.coinData} 
                  showBalance={this.state.showBalance}
                  handleRefresh={this.handleRefresh} 
        />
      </Div>
    );

  }
 
}

export default App;

2 Likes
2 Likes
var node = document.querySelector('.js-container');
var text = [];

Promise.all([
  axios.get('https://api.coinpaprika.com/v1/tickers/btc-bitcoin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/eth-etherium'),
  axios.get('https://api.coinpaprika.com/v1/tickers/bnb-binance')
  axios.get('https://api.coinpaprika.com/v1/tickers/xrp-ripple')
  axios.get('https://api.coinpaprika.com/v1/tickers/usdt-tether')

    ])
    .then( 
      (coinResponses) => {
      const coins = coinResponses.map( response =>
    <li>
      ${response.data.name} (${response.data.symbol});
      ${response.data.quotes['USD'].price}
     </li>
   ).join('');
      
      node.InnerHTML = `<ol>${coins}</ol>`;
  });
2 Likes

My solution is below

https://codepen.io/nige-n15/pen/YzNmvVM

2 Likes

https://codepen.io/Ultra-lord/pen/BaWBPdR

2 Likes
var node = document.querySelector('.js-container');
var text = []; 

Promise.all([
  axios.get('https://api.coinpaprika.com/v1/tickers/btc-bitcoin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/eth-ethereum'),
  axios.get('https://api.coinpaprika.com/v1/tickers/xrp-xrp'),
  axios.get('https://api.coinpaprika.com/v1/tickers/bch-bitcoin-cash'),
  axios.get('https://api.coinpaprika.com/v1/tickers/ada-cardano')
]);
  (coinsResponses) => {
    const coins = coinsResponses
    .map (response => `
        <li> 
          ${response.data.name} (${response.data.symbol}) :
          ${response.data.quotes['USD'].price}
         </li> `
         ).join('');
    node.innerHTML = `<ol> ${coins} </ol>`
  }
2 Likes

Complicated but I am starting to understand it a little.

var node = document.querySelector('.container');
axios.get('https://api.coinpaprika.com/v1/coins')

.then(response => response.data.slice(0,5)).then
(coins => 
Promise.all(
coins.map(
coin =>
axios.get(`https://api.coinpaprika.com/v1/tickers/${coin.id}`))))
.then(coins => coinList = coins.map(coin =>
 `<li>${coin.name} (${coin.symbol})$ 
${response.data.quotes['USD'].price}
</li>`);
console.log(node);
node.innerHTML = `<ol>${coinList.join('')}</ol>`;
}
);
2 Likes

Dear Zsolt
I am getting below error while code is trying to get data from the API. Please what could have caused it

GET https://api.coinpaprika.com/v1/tickers/ltc-litecoin 429
Uncaught (in promise) Error: Request failed with status code 429
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)

Its an error that occurs when you send a lot of requests at the same time. Make sure your for loop is not hitting the coinpaparika api many times in a single second.

Wait for a few minutes and the api will allow you to hit it again.

Hope this helps.

1 Like

Exactly. This is a problem especially when you develop with a live server or on CodeSandbox or CodePen.

I have had this problem before when I was a bootcamp instructor on a live session. After 5-10 minutes, I got banned from the API.

There is a hack obviously, you can fire up a VPN and you’re good to go for another 5-10 minutes on CodePen. :slight_smile:

2 Likes

Didn’t know that this was an assignment, grabbed the 10 coins so that I can reuse the links to the react-app. Here’s my assignment

image

In case you want to view the JS code better

JS code
var node = document.querySelector('.js-container');
var text =[];

Promise.all([
  axios.get('https://api.coinpaprika.com/v1/tickers/btc-bitcoin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/eth-ethereum'),
  axios.get('https://api.coinpaprika.com/v1/tickers/usdt-tether'),
  axios.get('https://api.coinpaprika.com/v1/tickers/bnb-binance-coin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/ada-cardano'),
  axios.get('https://api.coinpaprika.com/v1/tickers/xrp-xrp'),
  axios.get('https://api.coinpaprika.com/v1/tickers/doge-dogecoin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/dot-polkadot'),
  axios.get('https://api.coinpaprika.com/v1/tickers/hex-hex'),
  axios.get('https://api.coinpaprika.com/v1/tickers/bch-bitcoin-cash')
]).then(
  (coinResponses) => {
    const coins = coinResponses.map( response => `
      <li>
        ${response.data.name} (${response.data.symbol}):
        ${response.data.quotes['USD'].price}
      </li>` )
    .join('');
    node.innerHTML = `<ol>${coins}</ol>`;
  }
);
2 Likes

Here’s my solution:

https://codepen.io/rego350/pen/jOBKPxO?editors=1111
Screen Shot 2021-06-07 at 15.06.38

I had hard time using .then method. Using await makes it much easier to understand and makes the code much more readable.

3 Likes

Here is the assignment :
But I’ve one query in the below code. The last statement of js file, is printing an empty array.

console.log("here" + coin);

Can anybody resolve this as I have defined coin in the global scope and assigned some value later?

Below is the implementation of the same for app.js

componentDidMount = async() =>{

   var resp = await axios.get('https://api.coinpaprika.com/v1/coins');

   var coins = resp.data.slice(0,COIN_COUNT).map(coin => 
    axios.get(`https://api.coinpaprika.com/v1/tickers/${coin.id}`));
    Promise.all(coins).then(coinResponses => {
      var finalCoinData = coinResponses.map(response => {
        return {
         key : response.data.id,
         name : response.data.name,
         ticker : response.data.symbol,
         price : response.data.quotes.USD.price,
         balance : 0
        };
      })
      this.setState({coinData : finalCoinData});
    });
  }
1 Like

Hi @tanu_g,

The issue is not regarding the scope of the variable. It is actually the fact that you’re using promises to get and resolve data. That means its asynchronous. So, Console.log() statement gets called first and then the coin variable gets filled up.

To quickly check this you can add a console statement here as well as shown below-

var node = document.querySelector('.root');
var coin = [];
Promise.all([
 axios.get('https://api.coinpaprika.com/v1/tickers/btc-bitcoin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/eth-ethereum'),
  axios.get('https://api.coinpaprika.com/v1/tickers/usdt-tether'),
  axios.get('https://api.coinpaprika.com/v1/tickers/bnb-binance-coin'),
  axios.get('https://api.coinpaprika.com/v1/tickers/ada-cardano')
]).then(coinResponses => {
   coin = coinResponses.map(response => 
     `<li>${response.data.name} 
      (${response.data.symbol}) :      
      ${response.data.quotes.USD.price} 
      </li>`                         
     );
  node.innerHTML = `<ol>${coin.join("")}</ol>`;
console.log("here in promises" + coin);
});
console.log("here" + coin);

You will notice that the console.log after the promise statement gets called first. And then after the promises get resolved (aka get data from the api) the coin variable is populated.

Hope this makes sense. :slight_smile:

Thanks, @Malik.
I can figure it out now.

2 Likes