set token URI function

Viewed 2646

I understood that setTokenURI function isn't in use anymore. How can I change the token URI of the NFT token I want to create? for now my function createCollectible inside the smart contract looks like this:

function createCollectible(string memory tokenURI)
    public
    returns (uint256)
{
    uint256 newItemId = tokenId;
    _safeMint(msg.sender, newItemId);
    _setTokenURI(newItemId, tokenURI);
    tokenId = tokenId + 1;
    return newItemId;
}
1 Answers

_setTokenURI is still used but it is moved to the ERC721URIStorage. Here is the openzeppelin link

When you create your contract, you should inherit:

contract NFT is ERC721URIStorage { }

Since calling it an expensive operation, team wants you to use tokenUri function in ERC721:

function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

this time you need to inherit from ERC721

 contract NFT is ERC721{
    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
       require(_exists(tokenId), "...");
       _tokenURIs[tokenId] = _tokenURI;
           }
   }

They both have different use cases: Discussed Here

Related