[React-Moralis] Fetching the tokenUri from getUserItems in React from the Morarable Tutorials

I am trying to recreate the Morarable tutorial in React, and am unable to fetch the tokenUri when using the cloud function ā€œgetUserItemsā€.

The tokenUri (which is a JSON url that needs to be fetched within each item) as the following structure (dummy data) :

{"name":"NFT 1","description":"12323","image":"https://ipfs.moralis.io:2053/ipfs/HicrzX9ge8ywjRHQrikN1TtMRCJvym2cnXjfCiT"}

I am using a solution that was previously suggested to me (looping through the getUserItems function and extracting the data) the only issue now is that within the loop I also need to make a fetch request to the tokenUri in order to display the name, description and image stored on IPFS of the NFT. I am able to fetch the data wehn I console.log it, but Iā€™d like to save it in an array so I can access it via JSX.

Any thoughts?

import { useMoralis, useMoralisFile, useNewMoralisObject, useMoralisCloudFunction} from "react-moralis"
import {useState, useRef, useEffect} from 'react';
import Item from "./Item"
import { Button } from "@chakra-ui/button";
import { GetItems } from "./getItems";

export const UserItems = () => {

    const {data, error, isLoading} = useMoralisCloudFunction("getUserItems");
    
    let source = []
    for(var i = 0; i < data.length; i++) {
        var obj = data[i];
        (async () => {  
            try {  
              const res = await fetch(obj.tokenUri)
              const tokenInfo = await res.json()
              //console.log(Object.keys(tokenInfo).length)
              
            //   source = {name: tokenInfo["name"], description:tokenInfo["description"]}
                source.push(tokenInfo)
              
            } catch (err) {  
              throw err  
            }  
        })()
    }


    return (
        <>
        {
            source.map((item) => (
                item.name
            ))
        }

        </>
    )
}

Hey @achello

I suggest you to use Promise.all() intead of looping and waiting each element. Iā€™ve found for you an example

It will optimize and will speed up your code. And I misunderstood you a little. Do you want information about each nft to be all in one object?

Hey @Yomoo ,

thank you for the suggestion. Yes I want the information about each nft to be all in one object!

While I tried everything, I still cannot figure out how to do this because the problem is not about promises, what happens is that after I get the results from the promise i want to store the result inside a defined empty array. But after doing this, it gives me an array inside an empty array, which Iā€™m not able to operate on.

The desired output is

[{name:"NFT1", description:"description1", image:"ipfs url1"}, {{name:"NFT2", description:"description2", image:"ipfs url2"}}]

but what I got is:

This is my code:

    const {data, error, isLoading} = useMoralisCloudFunction("getUserItems");

    let obj = [];
    Promise.all(data.map(url => fetch(url.tokenUri)))
    .then(resp => Promise.all( resp.map(r => r.text()) ))
    .then(result => {
       obj.push(result)
    });

    console.log(obj)

For me it looks like you have strings there that need to be converted to json.

1 Like

the JSON is converted as a string yes, but im pushing each string object into an array from which i cannot get any information as it is contained in an empty array first,

If console.log shows it then it should be reachable

I think first check data is loaded

  const {data, error, isLoading} = useMoralisCloudFunction("getUserItems");

  useEffect(() => {
    if (data) {
       // Here your code
    }
  }, [data]);

The data is already loaded correctly, the problem is that im trying to push the data into an array

Solved by using state hooks instead of arrays

1 Like

Great job @achello :man_mechanic:

took me an entire months to figure out haha, useState and useEffect together do the trick. Its too bad there is not enough React support and all the videos are done in Vanilla JS instead, hopefully there will be more support in the future

1 Like

Sure, in our YouTube channel will be more videos for React.