# Alchemy Road to Web3- 第四周教程

By [HelloVipSir](https://paragraph.com/@hellovipsir) · 2022-10-14

---

![](https://storage.googleapis.com/papyrus_images/1c054dd55f6a8d753168765883588ce050b4ba11657a492dbd2ad1723a098396.png)

### step1 创建项目设置

1.打开控制台并输入以下代码，从而创建 Next JS 项目样板并安装 TailwindCSS。

npx create-next-app -e with-tailwindcss nameoftheproject ，如图。

![](https://storage.googleapis.com/papyrus_images/623c5cb219320437fa0c4b726b2dbc1eb2434dd9763b4e69968852ae491fec35.png)

2.输入cd nameoftheproject && code . （最后那个点别掉了，掉了打开的就是之前的项目）

![](https://storage.googleapis.com/papyrus_images/d75914894ef20e02902479c4beeb12663f7ddc2bab7104043402ef964aa39aa7.png)

3.在控制台输入npm run dev ，如果电脑弹出防火墙，就点允许访问，不弹出也没关系。

![](https://storage.googleapis.com/papyrus_images/8bf186a6794f900393fd3f9df465489d26213fe4e6fe7c0bc7ff2975aecea0e0.png)

4.回到vscode，将index.tsx和\_app.tsx的后缀改成.jsx，删除\_app.jsx中报错的部分，如图。

或者直接粘贴下面的代码替换。

![](https://storage.googleapis.com/papyrus_images/c9051fa275d9051dc8effb67f631b7b2b75c6cc87096eb44a572cb5b094648b9.png)

    import '../styles/globals.css'
    function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />
    }
    export default MyApp
    

### step2 修改index.jsx代码

1.**这一步具体每行代码的意义可以到官方看，我这里放最终的代码，方便大家完成任务，但是这对于学习web3是毫无作用的**。将index.jsx的代码更改成如下代码。如图。

    import { NFTCard } from "./nftCard"
    import { useState } from 'react'
    
    const Home = () => {
     const [wallet, setWalletAddress] = useState("");
     const [collection, setCollectionAddress] = useState("");
     const [NFTs, setNFTs] = useState([])
     const [fetchForCollection, setFetchForCollection]=useState(false)
    
    
      const fetchNFTs = async() => {
        let nfts; 
        console.log("fetching nfts");
        const api_key = "75dGSnZXuLyiwz-TRVYrJAhhZthlG9Tj"
        const baseURL = `https://eth-mainnet.alchemyapi.io/v2/${api_key}/getNFTs/`;
        var requestOptions = {
            method: 'GET'
          };
         
        if (!collection.length) {
        
          const fetchURL = `${baseURL}?owner=${wallet}`;
      
          nfts = await fetch(fetchURL, requestOptions).then(data => data.json())
        } else {
          console.log("fetching nfts for collection owned by address")
          const fetchURL = `${baseURL}?owner=${wallet}&contractAddresses%5B%5D=${collection}`;
          nfts= await fetch(fetchURL, requestOptions).then(data => data.json())
        }
      
        if (nfts) {
          console.log("nfts:", nfts)
          setNFTs(nfts.ownedNfts)
        }
      }
      
      const fetchNFTsForCollection = async () => {
        if (collection.length) {
          var requestOptions = {
            method: 'GET'
          };
          const api_key = "75dGSnZXuLyiwz-TRVYrJAhhZthlG9Tj"
          const baseURL = `https://eth-mainnet.alchemyapi.io/v2/${api_key}/getNFTsForCollection/`;
          const fetchURL = `${baseURL}?contractAddress=${collection}&withMetadata=${"true"}`;
          const nfts = await fetch(fetchURL, requestOptions).then(data => data.json())
          if (nfts) {
            console.log("NFTs in collection:", nfts)
            setNFTs(nfts.nfts)
          }
        }
      }
    
     return (
       <div className="flex flex-col items-center justify-center py-8 gap-y-3">
         <div className="flex flex-col w-full justify-center items-center gap-y-2">
         <input disabled={fetchForCollection} type={"text"} placeholder="Add your wallet address" onChange={e => setWalletAddress(e.target.value)} value={wallet}></input>
           <input type={"text"} placeholder="Add the collection address"></input>
           <label className="text-gray-600 "><input onChange={(e)=>{setFetchForCollection(e.target.checked)}} type={"checkbox"} className="mr-2"></input>Fetch for collection</label>
           <button className={"disabled:bg-slate-500 text-white bg-blue-400 px-4 py-2 mt-3 rounded-sm w-1/5"} onClick={
              () => {
               if (fetchForCollection) {
                 fetchNFTsForCollection()
               }else fetchNFTs()
             }
           }>Let's go! </button>
         </div>
         <div className='flex flex-wrap gap-y-12 mt-4 w-5/6 gap-x-2 justify-center'>
           {
             NFTs.length && NFTs.map(nft => {
               return (
                 <NFTCard nft={nft}></NFTCard>
               )
             })
           }
         </div>
       </div>
     )
    }
    
    export default Home
    

![](https://storage.googleapis.com/papyrus_images/ad31cb506e7a8802fb62da5066e7056214ed39d16a8e018d91051e4d0fde6a1e.png)

### step3 创建一个新的炼金术应用程序

1.进入[alchemy.com](https://alchemy.com/?a=cn-road-to-week-four) ，点击create app。

![](https://storage.googleapis.com/papyrus_images/caf7e0ef08cf5a82808fd82209dd36042b78a39625efb711a19991c42e4c2787.png)

2.输入信息，点击create app。

![](https://storage.googleapis.com/papyrus_images/46342f9b5c3ef2448435601c0d45c81369a1b9b0e15e13831b8f431976081cfb.png)

3.点击view key，将红框内的API KEY复制下来。

![](https://storage.googleapis.com/papyrus_images/6c57e9752e73e6c265948bf06095544a9a505099aef7b5cb16f3880d974c2c99.png)

4.回到vscode，在index.jsx中ctrl+f搜索const api\_key，应该会搜索到2处，全部改成上一步复制的代码，然后保存。

![](https://storage.googleapis.com/papyrus_images/6f9b269790377ff715e61a430492fece352ab94b236e9952baaa24c06bdd3eb8.png)

### step4 创建 NFT Card 组件

1.在pages下面新建一个名为nftCard.jsx的文件，并将下面的代码粘贴进去。

![](https://storage.googleapis.com/papyrus_images/06019ef6b110a73687a8010bea83999de72e2f2bbf23fe09a017d6078cf2fadc.png)

    export const NFTCard = ({ nft }) => {
    
        return (
            <div className="w-1/4 flex flex-col ">
            <div className="rounded-md">
                <img className="object-cover h-128 w-full rounded-t-md" src={nft.media[0].gateway} ></img>
            </div>
            <div className="flex flex-col y-gap-2 px-2 py-3 bg-slate-100 rounded-b-md h-110 ">
                <div className="">
                    <h2 className="text-xl text-gray-800">{nft.title}</h2>
                    <p className="text-gray-600">Id: {nft.id.tokenId}</p>
                    <p className="text-gray-600" >{nft.contract.address}</p>
                </div>
    
                <div className="flex-grow mt-2">
                    <p className="text-gray-600">{nft.description}</p>
                </div>
            </div>
    
        </div>
        )
    }
    

### step5 运行测试

1.在控制台输入cd nameoftheproject，按回车，然后输入npm run dev，如图所示即可。

![](https://storage.googleapis.com/papyrus_images/322d0d6ed18c8b5f415cd0b05d17b518f89955ae39c85adc8b3f278bd9e7871f.png)

2.然后将[http://localhost:3000](http://localhost:3000/) （我这里是这个链接，我看官方视频是3001，可能会不一样啊，我也不知道哈哈），就是上面那个图的第一行的链接，复制到浏览器。出现下图即可。

![](https://storage.googleapis.com/papyrus_images/b711e04c1ad87ab0025e0f5ee7e488b2c5116c0ca9d5c4f7fb4aba5f73d528d6.png)

3.输入你自己的地址，点击let‘s go，下面出现图片即可。

![](https://storage.googleapis.com/papyrus_images/c6bf09f787d31299fa7d38dae764a8450dce232180750051e404f81ba6227352.png)

### step6 上传至github

### step7 项目提交

直接填写上传的项目的github网址即可。

---

*Originally published on [HelloVipSir](https://paragraph.com/@hellovipsir/alchemy-road-to-web3)*
