How to define the correct interface and loop over the data in React?

Viewed 87

I am kinda new to Typescript. Here I have a simple API, and I want to iterate through, and display the data. You can go to the API link and see the raw data. I would be really grateful for some help.

Interfaces:

export interface ITrending {
  coins: IItem[]
}

export interface IItem {
  item: {
    id: string;
    name: string;
    symbol: string;
    market_cap_rank: number;
    thumb?: string;
    large?: string
  } 
}

React Code:

import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { ITrending } from '../interfaces'
const TRENDING = 'https://api.coingecko.com/api/v3/search/trending'
const Home = () => {
  const [trending, setTrending] = useState<ITrending[]>([])
  useEffect(() => {
    axios.get<ITrending[]>(TRENDING).then((response) => {
      setTrending(response.data)
      console.log(response.data)
    })
  }, [])

  return <div></div>
}

export default Home

Sample API response:

{
   "coins":[
      {
         "item":{
            "id":"superfarm",
            "name":"SuperFarm",
            "symbol":"SUPER",
            "market_cap_rank":235,
            "thumb":"https://assets.coingecko.com/coins/images/14040/thumb/6YPdWn6.png?1613975899",
            "large":"https://assets.coingecko.com/coins/images/14040/large/6YPdWn6.png?1613975899",
            "score":0
         }
      },
      {...}
   ],
   "exchanges":[]
}
1 Answers

As the coins are inside of data.coins, you need to have it this way:

import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { ITrending } from '../interfaces'
const TRENDING = 'https://api.coingecko.com/api/v3/search/trending'
const Home = () => {
  const [trending, setTrending] = useState<ITrending[]>([])
  useEffect(() => {
    axios.get<ITrending[]>(TRENDING).then((response) => {
      setTrending(response.data.coins)
      console.log(response.data)
    })
  }, [])

  return <div>{trending.map(t => (<div key={t.item.id}>{t.item.name}</div>)}</div>
}

export default Home
Related