I am trying to fetch the image and data which is uploaded to IPFS using Pinata endpoints but I am not able to load it and its showing failed to fetch at LoadNFTs(this is the function name),
here is the code for uploading the file to the ipfs :
const uploadToIPFS = async (event) => {
event.preventDefault();
const file = event.target.files[0];
if (typeof file !== 'undefined') {
const formData = new FormData();
formData.append('file', file);
try {
const resFile = await axios({
method: 'post',
url: 'https://api.pinata.cloud/pinning/pinFileToIPFS',
data: formData,
headers: {
'pinata_api_key': REACT_APP_PINATA_API_KEY,
'pinata_secret_api_key': REACT_APP_PINATA_API_SECRET,
'Content-Type': 'multipart/form-data'
}
});
const ImgHash = `ipfs://${resFile.data.IpfsHash}`;
setAvatar(ImgHash);
console.log("IPFS image upload succesfully")
} catch (error) {
console.log('Pinata IPFS image upload error: ', error);
}
}
};
below is the code of MintProfile function :
const mintProfile = async (event) => {
if (!avatar || !username) return;
try {
const formData = new FormData();
formData.append('file', JSON.stringify({ avatar, username }));
const resFile = await axios({
method: 'post',
url: 'https://api.pinata.cloud/pinning/pinJSONToIPFS',
data: formData,
headers: {
'pinata_api_key':REACT_APP_PINATA_API_KEY,
'pinata_secret_api_key':REACT_APP_PINATA_API_SECRET,
'Content-Type': 'application/json',
},
});
setLoading(true);
const uri = `ipfs://${resFile.data.IpfsHash}`;
console.log("error first")
await (await contract.mint(uri)).wait();
console.log("error second")
loadMyNFTs();
} catch (error) {
console.log('Pinata IPFS URI upload error: ', error);
window.alert('There was an error minting your NFT. Please try again later.');
}
};
On the screen its just showing loading....
and this is LoadMyNfts function:
const loadMyNFTs = async () => {
// Get users nft ids
const results = await contract.getMyNfts();
// Fetch metadata of each nft and add that to nft object.
let nfts = await Promise.all(results.map(async i => {
// get uri url of nft
const uri = await contract.tokenURI(i)
// fetch nft metadata
const response = await fetch(uri)
const metadata = await response.json()
return ({
id: i,
username: metadata.username,
avatar: metadata.avatar
})
}))
setNfts(nfts)
getProfile(nfts)
}
when you fetch from pinata, you should add proper header. from here
your code should be
another issue is in the
results.map
. when youmap
the array, the first argument of the callback is each element in the array and the second argument of the callback is the index. should be like this