rohit
rohit

Reputation: 179

.map is not a function react, axios problem

I am having a bit of a problem using the map function.

In the below code I am fetching NFT data through a rarible api using Axios (Works perfectly fine, I get a promise with the object as a response)

import Link from 'next/link'
import { useWeb3Context } from '../../context'
import { Web3Button } from '../../components'
import axios from 'axios'
import React, { useState } from 'react'
import NFTContainer from '@/components/NFTContainer'

const renderNotConnectedContainer = () => <Web3Button />

const fetchOwnedTokens = async (owner) => {
  try {
    const result = await axios.get(`https://ethereum-api.rarible.org/v0.1/nft/items/byOwner?owner=${owner}`)

    return [result.data.items]
  } catch (err) {
    console.error(err)
    return []
  }
}

export const ChooseProductView = () => {
  const { address } = useWeb3Context()

  if (!address) {
    return renderNotConnectedContainer()
  } else {
    const data = fetchOwnedTokens(address)
    console.log(data)

    return (
      <div className="flex items-center justify-center">
        <NFTContainer nfts={data} />
      </div>
    )
  }
}

Then I am trying to pass the response to a container file using props, but I get an error --Unhandled Runtime Error TypeError: nfts.map is not a function which I think is because NFTs are not of an array datatype. Any suggestions, please? Have been stuck for a while

import React from 'react'
import NFTCard from './NFTCard'

const NFTContainer = ({ nfts }) => {
  return (
    <div>
      {nfts.map((nft, index) => (
        <NFTCard nft={nft} key={index} />
      ))}
    </div>
  )
}

export default NFTContainer

Upvotes: 0

Views: 633

Answers (1)

Arezou Saremian
Arezou Saremian

Reputation: 508

You can not use map on object so you should convert it :

<div>
  {Object.keys(nfts).map((nft, index) => (
    <NFTCard nft={nft} key={index} />
  ))}
</div>

Upvotes: 1

Related Questions