royalTiger
royalTiger

Reputation: 1

Map through an array of objects NextJs

I am working on building an application in NextJS where I have to fetch coinmarketcap api in order to display the top 10 cryptocurrencies name and price. I created another file in the api folder containing the private key called coin-market-cap-api.ts. I can see the data is displayed as an object so how can I map through it and take out the cryptocurrency name and price? I tried using state but it is showing me an error, I also tried props but I cannot get to display anything. I also get an error when I try to map through with 500 (Internal Server Error). I think the problem is the way how I am passing the data but I am not sure where the mistake is HomePageHeader.tsx

import Image from 'next/image';
import { navLinks } from './data';
import { LatestCrypto } from './latestCrypto';
import { Col, Row } from 'antd';
import React, { useEffect, useState } from 'react';

export const HomePageHeader = () => {
  const [crypto, setSelectedCrypto] = React.useState();

  fetch('/api/coin-market-cap-api')
  .then((res)=>res.json())
  .then((data)=>{
    console.log("printed data", data);
     setSelectedCrypto(data)  
  })
  .catch((err)=>{
    console.log(err)
  })
console.log("stats", setSelectedCrypto)
  return (
    <Row>
      <Col md={24} sm={24} xs={24} className='homepage-header'>
        <div id='logo'>
          <Image src='/Logo_neon.png' alt='logo' className='logo-img' width={150} height={50} />
        </div>
        <div className='ticker-tape-section'>
          <div className='ticker-tape-section__container'>
            <div className='ticker-tape__text-block'>
              {navLinks.map((link, index) => {
                return (
                  <div className='cont' key={index}>
                    <span className='ticker-tape--text'>{link.name}</span>
                    <span className='ticker-tape--text'>{link.price}</span>
                  </div>
                );
              })}
            </div>
            <div className='ticker-tape__text-block'>
              {crypto.map((link, index) => {
                return (
                  <div className='cont' key={index}>
                    <span className='ticker-tape--text'>{link.name}</span>
                    <span className='ticker-tape--text'>{link.price}</span>
                  </div>
                );
              })}
            </div> 

          </div>
        </div>
      </Col>
    </Row>
  );
};

coin-market-cap-api.ts

import axios from 'axios';
import { NextApiRequest, NextApiResponse } from 'next';
const API_PRIVATE_KEY = process.env.NEXT_PRIVATE_CRYPRO_MARKET_KEY;

export default async function getTop10Coin(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    const response = await axios.get(
      'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=10&convert=USD',
      {
        headers: {
          'X-CMC_PRO_API_KEY': `${API_PRIVATE_KEY}`,
        },
      }
    );
    return res.json(response.data.data);
  }
  return res.json({ message: 'Somethin went wrong' });
}

output

Array(10)
0: {id: 1, name: 'Bitcoin', symbol: 'BTC', slug: 'bitcoin', num_market_pairs: 9713, …}
1: {id: 1027, name: 'Ethereum', symbol: 'ETH', slug: 'ethereum', num_market_pairs: 6066, …}
2: {id: 825, name: 'Tether', symbol: 'USDT', slug: 'tether', num_market_pairs: 39089, …}
3: {id: 3408, name: 'USD Coin', symbol: 'USDC', slug: 'usd-coin', num_market_pairs: 6051, …}
4: {id: 1839, name: 'BNB', symbol: 'BNB', slug: 'bnb', num_market_pairs: 1091, …}
5: {id: 4687, name: 'Binance USD', symbol: 'BUSD', slug: 'binance-usd', num_market_pairs: 4945, …}
6: {id: 52, name: 'XRP', symbol: 'XRP', slug: 'xrp', num_market_pairs: 809, …}
7: {id: 2010, name: 'Cardano', symbol: 'ADA', slug: 'cardano', num_market_pairs: 564, …}
8: {id: 5426, name: 'Solana', symbol: 'SOL', slug: 'solana', num_market_pairs: 372, …}
9: {id: 74, name: 'Dogecoin', symbol: 'DOGE', slug: 'dogecoin', num_market_pairs: 556, …}
length: 10

Many Thanks everyone

Upvotes: 0

Views: 1056

Answers (1)

L&#225;zaro Souza
L&#225;zaro Souza

Reputation: 31

Maybe this can help you

 Object.keys(object).map(item => item);

I think it will be helpful if you print here the JSON returned :D

Upvotes: 0

Related Questions