2

I built a ui on next js using typescript and need the items available count to not only show currently available items but to update after a user mints. Currently, I'm using candyMachine.data.itemsAvailable which shows a total number of items inserted into the candy machine instead of the current available count. I'm using import { CandyMachine } from "@metaplex-foundation/mpl-candy-machine" to work functions.

const CarMint = () => {
  const wallet = useWallet();
  const [pageLoading, setPageLoading] = useState<boolean>(true);
  const [candyMachine, setCandyMachine] = useState<CandyMachine | undefined>();
  const [isUserMinting, setIsUserMinting] = useState(false);
  const owner = publicKey("walletaddress");
  const { enqueueSnackbar } = useSnackbar();
  const umi = createUmi(process.env.NEXT_PUBLIC_SOLANA_RPC_HOST as unknown as string)
  .use(walletAdapterIdentity(wallet))
  .use(mplCandyMachine());

  const getCandyMachine = async () => {
    setPageLoading(true);
    try {
      const cmPubkey = publicKey(
        CarCandy ?? ""
      );
      const candyMachine = await fetchCandyMachine(umi, cmPubkey);
      if (!candyMachine) throw new Error("No Candymachine at address");
      setCandyMachine(candyMachine);
    } catch (error) {
      console.log("Fetching CM Error", error);
      enqueueSnackbar(
        "Fetching CM Error: Check console logs for more details",
        {
          variant: "error",
          anchorOrigin: { vertical: "top", horizontal: "right" },
        }
      );
    }
  
    setPageLoading(false);
  };
  
  useEffect(() => {
    getCandyMachine();
  }, []);



  const getPayMintButtonContent = () => {
    if (!candyMachine) {
      return "Loading...";
    }

    if (isUserMinting) {
      return "Minting in progress..";
    } else if (candyMachine.data.itemsAvailable === BigInt(0)) {
      return "Sold out";
    } else {
      return "Free Mint";
    }
  };

  const payMintButtonClicked = async () => {
    setIsUserMinting(true);
    try {
      if (candyMachine?.publicKey) {
        const nftMint = generateSigner(umi);
    const freeMint = await transactionBuilder()
      .add(setComputeUnitLimit(umi, { units: 800_000 }))
      .add(
        mintV2(umi, {
          candyMachine: candyMachine.publicKey,
          nftMint,
          collectionMint: candyMachine.collectionMint,
          collectionUpdateAuthority: owner,
          mintArgs: {
            mintLimit: some({ id: 1 }),
            solPayment: some({ destination: owner }),
          },
          tokenStandard: TokenStandard.ProgrammableNonFungible,
        })
      )
      .sendAndConfirm(umi);
    
      console.log( "Mint Success!!!", freeMint )
      enqueueSnackbar(
        "Mint Success!!!",
        {
          variant: "success",
          anchorOrigin: { vertical: "top", horizontal: "right" },
        }
      );
      getCandyMachine();
      }
    } catch (error) {
      console.error("Mint Error", error);
      enqueueSnackbar("Mint Error: Only one per customer, Dude!!!", {
        variant: "error",
        anchorOrigin: { vertical: "top", horizontal: "right" },
      });
    }
    setIsUserMinting(false);
  };

return (
                <Grid item xs={3}>
                  <Typography variant="body2" color="#ffd839" style={{
                      textAlign: "center", fontFamily: "Press Start 2P"
                    }}>
                    Remaining
                  </Typography>
                  <Typography
                    variant="h6"
                    color="textPrimary"
                    style={{
                      fontWeight: "bold",
                      textAlign: "center",
                    }}
                  >
                    {`${candyMachine ? candyMachine.data.itemsAvailable : "Loading.."}`}
                  </Typography>
                </Grid>

2 Answers 2

1

The presented code does refresh after mint occurs, the problem is with "candyMachine.data.itemsAvailable" It shows the total amount inserted into the candyMachine. Use candyMachine.itemsRedeem and it will give you a count that increases to the total compared to a count that decreases. Anyone wanting to use this code will need to change (candyMachine.data.itemsAvailable === BigInt(0)) to (candyMachine.itemsAvailable === BigInt("Your total number"))

0

Tx confirmation takes some time so you need to add something like "await delay(5000)" before fetching Candymachine whenever you mint

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.