본문 바로가기
프로그래밍/solidity

[220517] 민팅한 결과에 맞는 이미지를 가져오기

by 한코코 2022. 5. 17.

1.   내가 민팅해서 갖고있는 nft개수 확인하기

nft를 총 1개 갖고있다.

 

 

2.   방금 민팅한 tokenId 확인하기

나는 nft를 1개 갖고있으므로 index 상 0번에 해당한다.

index[0]에 해당하는 nft의 tokenId는 1이다.

 

 

3.   tokenId가 갖고있는 값 확인하기

동물을 1~5번으로 나누어놓은 animalTypes에서 3번째 동물이 나온것을 알 수 있다.

 

 

민팅한 결과와 맞는 이미지를 가져오는 코드

Main.tsx

//typescript 사용하려면 FC
import React,{FC, useState} from 'react'
import { Box, Text, Flex, Button } from "@chakra-ui/react";
import { mintAnimalTokenContract } from "../web3Config";
import AnimalCard from "../components/AnimalCard";

interface MainProps { account: string; }

const Main: FC<MainProps> = ({account}) => {
  const [newAnimalType, setNewAnimalType] = useState<string>();

  const onClickMint = async () => {
    try {
      if (!account) return;

      const response = await mintAnimalTokenContract.methods
        .mintAnimalToken()
        .send({ from: account });

        // status가 true일때 실행
        if(response.status){
          // 1. 내가 민팅해서 갖고있는 nft개수 확인
          // balanceOf에서 주소 넣었던 기능 구현
          const balanceLength = await mintAnimalTokenContract.methods
          .balanceOf(account)
          .call(); // call 버튼 누른것 구현

          // 2. 방금 민팅한 tokenId 확인하기
          const animalTokenId = await mintAnimalTokenContract.methods
          // string으로 목록이 들어오기때문에 -> 10진수로 형변환
          .tokenOfOwnerByIndex(account, parseInt(balanceLength, 10) - 1)
          .call();

          // tokenId가 갖고있는 값 확인하기
          const animalType = await mintAnimalTokenContract.methods
          .animalTypes(animalTokenId)
          .call();

          setNewAnimalType(animalType);
        }

      console.log(response);
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <Flex
      w="full"
      h="100vh"
      justifyContent="center"
      alignItems="center"
      direction="column"
    >
      <Box>
      {newAnimalType
      ? (<AnimalCard animalType={newAnimalType} />)
      : (<Text>Let's mint Animal Card!!!</Text>)}
      </Box>
      <Button mt={4} size="sm" colorScheme="blue" onClick={onClickMint}>
        Mint
      </Button>
    </Flex>
  );
};

export default Main;

 

 

AnimalCard.tsx

import React, { FC } from "react";
import { Image } from "@chakra-ui/react";
// AspectRatio 가로세로 고정이미지 비율 건들때 사용

interface AnimalCardProps {
  animalType: string;
}

const AnimalCard: FC<AnimalCardProps> = ({ animalType }) => {
  return (
    <Image w={150} h={150} src={`images/${animalType}.png`} alt="AnimalCard" />
  );
};

export default AnimalCard;

 

 

github

https://github.com/h662/h662Animals-frontend/commit/413979555163827915a4525e007917a3cba90266

댓글