[id].js page not loading other routes in the same directory

This is the code to my [id].js - although it works… It has some issues. For instance - once visiting an id (being a collection address), visiting a different id does not work - no errors, the second id just does not load… I know I need to add a getStaticProps and getStaticpaths however when I do so I get an error in my getStaticProps regarding moralis… Would this fix the issue and if so how would I go about it in this context? Thanks

const Collection = () => {
  const [nftBalances, setNftBalances] = useState([]);
    
    const {Web3Api} = useMoralisWeb3Api();
  const {isInitialized, Moralis, account,isWeb3Enabled, enableWeb3} = useMoralis()
    const router=useRouter()
    const id = router.query.id
    console.log(account)
    
    const fetchContract = async()=>{
    const options = {
        chain: "rinkeby",
        address: id,
      };
      const nfts = await Moralis.Web3API.token.getAllTokenIds(options);
      let nftBalance = nfts.result;
    
    setNftBalances(nftBalance)
    }
    
    useEffect(() => {
        if (!isInitialized && !isWeb3Enabled) {
            
            enableWeb3()
        }
        else{
          fetchContract()
        }
    }, [isInitialized] && [isWeb3Enabled])

return()

I know I need to add a getStaticProps and getStaticpaths however when I do so I get an error in my getStaticProps regarding moralis

What is the error you get?

Do you get errors with your existing code?

Your code using useRouter should be fine for what you want, but you should add id to your useEffect so only call the API if isInitialized is true and if id is valid (not null/undefined).

Also, your dependencies should be like [isInitialized, isWeb3Enabled, id].

Thank you! it is sorted… Error is semi-resolved… The one thing I am unable to figure out is out to limit paths (example only be able to pull up 5 collections and if any other token address is entered get a 404 page) using the format I am using above

In the useEffect you’re using, you could add another condition and check if the id matches any of the 5 addresses. There’s probably a more elegant way of doing this in Next.js but that would be fine.

And then just redirect the user to the 404 page e.g. with router.push if the address isn’t allowed.

1 Like