在NextJS中呈现异步数据获取

r55awzrz  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(116)
export default async function Page() {
  const endpoint = `https://${process.env.NEXT_PUBLIC_RPC_URL}`;
  const cmId = process.env.NEXT_PUBLIC_CANDY_MACHINE_ID? process.env.NEXT_PUBLIC_CANDY_MACHINE_ID : '';

let umi: Umi = createUmi(endpoint)
.use(mplTokenMetadata())
.use(mplCandyMachine());

const [nfts, setNfts] = useState<NFT[]>([]);
const [uris, setUris] = useState<string[]>([]);
const [loading, setLoading] = useState(true)

useEffect(() => {
  const getNFTs = async () => {
    await fetchCandyMachine(umi, publicKey(cmId))
      .then(cm => cm.items)
      .then(items => items.map(item => setUris(prevUris => [...prevUris, item.uri])));

    for (const uri of uris) {
      await fetch(uri)
        .then(response => response.json())
        .then(json => {
          let nft = {
            name: json.name,
            symbol: json.symbol,
            description: json.description,
            image: json.image
          }
          setNfts(prevNfts => [...prevNfts, nft]);
        })
    }

  }

  getNFTs()
  .then(e => setLoading(false));
}, []);

return(
  <div>
  <div>
  <Link href='/'>Home</Link>
  </div>
  {loading && 
   <div>Loading...</div>
  }
  {!loading && nfts.map((nft, index) => (
  <div key={index}>
    <Image src={nft.image} alt={nft.name} width={500} height={300} />
  </div>
))}
  </div>
)

  }

字符串
你好,我已经写了这段代码,应该获取所有与uri相关的nfts元数据,然后渲染与nfts相关的图像……问题是页面仍然停留在加载中。分量BC,数据获取从未被解决。如何确保useEffect解析?
我尝试将所有获取的数据封装到useEffect钩子中定义的异步函数中。我希望呈现根据isLoading的值动态更改,但这个变量仍然停留在true上

uurv41yg

uurv41yg1#

这是我的解决方案。

useEffect(() => {
  const getNFTs = async () => {
    const candyMachine = await fetchCandyMachine(umi, publicKey(cmId));
    const itemUris = candyMachine.items.map(item => item.uri);
    const metadataPromises = itemUris.map(uri => fetch(uri).then(response => response.json()));
    const metadata = await Promise.all(metadataPromises);
    const nfts = metadata.map(json => ({
      name: json.name,
      symbol: json.symbol,
      description: json.description,
      image: json.image
    }));
    setNfts(nfts);
    setLoading(false);
  };

  getNFTs();
}, []);

字符串
希望这一个能帮助你

相关问题