I am currently building a gallery view of cards that receive images from axios api call.
I make the call in a useffect hook and then pass the resultant object to useState to be stored.
I then access the contents of the stored object with urls.map, but I get the following error -->
Uncaught TypeError: urls.map is not a function
End goal is to be able to pass the urls from the array objects (path data.nfts.media[0].uri) to the NFTCard component with props. Tested props, they are working.
This is the object that I am trying to filter through
import axios from "axios";
import React, { useEffect, useState } from "react";
import NFTCard from "./NFTCard";
function ViewNFT() {
const api_key = "witheld for privacy";
const address = "witheld for privacy";
const [urls,setUrls] = useState([])
useEffect(() => {
axios
.get(
`https://flow-testnet.g.alchemy.com/v2/${api_key}/getNFTs/?owner=${address}&offset=0&limit=10`
)
.then(res=> {
setUrls(...res.data.nfts);
console.log(res.data.nfts);
})
.catch(err=> {
console.log(err);
})
},[]);
return (
<>
{urls.map((url,id)=>{
return <div key={id}>
<NFTCard pharaoh_url={url} />
</div>
})}
</>
);
}
export default ViewNFT;
CodePudding user response:
The set function (setUrls
in this case) returned by useState
accepts a single parameter - either a value or a function. When you spread the array you get from the api
, the only item that is stored is the first object, and since it's not an array it doesn't have the Array.map()
method.
Remove the spread params from this line - setUrls(...res.data.nfts);
so it would store the entire array - setUrls(res.data.nfts);
.
If you want to make a shallow copy of the array returned by the api (redundant unless used in multiple states), spread into a new array - setUrls([...res.data.nfts]);
CodePudding user response:
try this plz
return (
<>
{urls && urls.length && urls.map((url,id)=>{
return <div key={id}>
<NFTCard pharaoh_url={url} />
</div>
})}