Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useNFTTokenIds hook #217

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ function App() {
- [`useNativeBalance()`](#usenativebalance)
- [`useNativeTransactions()`](#usenativetransactions)
- [`useNFTBalances()`](#usenftbalances)
- [`useNFTTokenIds()`](#usenfttokenids)
- [`useNFTTransfers()`](#usenfttransfers)
- [`useTokenPrice()`](#usetokenprice)
- [`useWeb3Contract()`](#useweb3contract)
Expand Down Expand Up @@ -1309,6 +1310,87 @@ const NFTBalances = () => {
}
```

### `useNFTTokenIds()`

Gets NFTs from the contract address. Supports both ERC721 and ERC1155. Returns an object with the total number of tokens and the array of NFT objects.

**Options**:
- `address`: A contract address (i.e. 0x1a2b3x...).
- `chain` (optional): The blockchain to get data from. Valid values are listed on the [Web3 API Intro page](https://docs.moralis.io/moralis-server/web3-sdk/intro#supported-chains). Default value: current chain (if the chain is not supported it will use the Eth chain).
- `limit` (optional): Number of NFTs to fetch. Default value: 5

**Example**
```jsx
import { useNFTTokenIds } from "react-moralis";

const { getNFTTokenIds, data, error, isLoading, isFetching } = useNFTTokenIds();

const NFTTokenIds = () => {
return (
<div>
{error && <>{JSON.stringify(error)}</>}
<button onClick={() => getNFTTokenIds({
address: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",
chain: "0x1",
limit: 1 })}>Refetch NFTBalances</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
```

**Example return** (Object)
```json
{
"total": "10000",
"page": 0,
"page_size": 1,
"cursor": "...",
"result": [
{
"token_address": "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",
"token_id": "9989",
"amount": "1",
"contract_type": "ERC721",
"name": "BoredApeYachtClub",
"symbol": "BAYC",
"token_uri": "https://gateway.moralisipfs.com/ipfs/QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq/9989",
"metadata": {
"image": "ipfs://QmRixhzz7vuF7Lq1h9XrH8rCyL7kGBZRf3i79ArqDmk7eN",
"attributes": [
{
"trait_type": "Clothes",
"value": "Vietnam Jacket"
},
{
"trait_type": "Hat",
"value": "Faux Hawk"
},
{
"trait_type": "Mouth",
"value": "Bored Pizza"
},
{
"trait_type": "Fur",
"value": "Red"
},
{
"trait_type": "Eyes",
"value": "Bored"
},
{
"trait_type": "Background",
"value": "New Punk Blue"
}
]
},
"synced_at": "2022-03-10T17:18:56.558Z",
"image": "ipfs://QmRixhzz7vuF7Lq1h9XrH8rCyL7kGBZRf3i79ArqDmk7eN"
}
]
}
```

### `useNFTTransfers()`

Gets the NFT transfers. Returns an object with the number of NFT transfers and the array of NFT transfers.
Expand Down
1 change: 1 addition & 0 deletions src/hooks/web3ApiWrappers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from "./useApiContract";
export * from "./useERC20Balances";
export * from "./useERC20Transfers";
export * from "./useNFTBalances";
export * from "./useNFTTokenIds";
export * from "./useNFTTransfers";
export * from "./useNativeBalance";
export * from "./useNativeTransactions";
Expand Down
1 change: 1 addition & 0 deletions src/hooks/web3ApiWrappers/useNFTTokenIds/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useNFTTokenIds";
68 changes: 68 additions & 0 deletions src/hooks/web3ApiWrappers/useNFTTokenIds/useNFTTokenIds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useMemo } from "react";
import MoralisType from "moralis";
import { useMoralis } from "../../core/useMoralis";
import {
useMoralisWeb3Api,
useMoralisWeb3ApiCall,
UseMoralisWeb3ApiCallOptions,
} from "../../core/useMoralisWeb3Api";
import { resolveIPFS } from "../../../functions/resolveIPFS";
import { DEFAULT_API_CHAIN } from "../../../config";
import { isValidApiChain } from "../../../utils/isValidApiChain";

export interface UseNFTTokenIdsParams
extends Omit<
Parameters<typeof MoralisType.Web3API["token"]["getAllTokenIds"]>[0],
"address" | "limit"
> {
address: string;
limit?: number;
}

export const useNFTTokenIds = (
params?: UseNFTTokenIdsParams,
options?: UseMoralisWeb3ApiCallOptions,
) => {
const { token } = useMoralisWeb3Api();
const { chainId } = useMoralis();

const {
fetch: getNFTTokenIds,
data,
error,
isLoading,
isFetching,
} = useMoralisWeb3ApiCall(
token.getAllTokenIds,
{
chain: params?.chain ?? isValidApiChain(chainId) ?? DEFAULT_API_CHAIN,
address: params?.address ?? "",
limit: params?.limit ?? 5,
...params,
},
{ autoFetch: options?.autoFetch ?? !!token, ...options },
);

const NFTTokenIds = useMemo(() => {
if (!data?.result || !data?.result.length) {
return data;
}

const formattedResult = data.result.map((nft) => {
try {
if (nft.metadata) {
const metadata = JSON.parse(nft.metadata);
const image = resolveIPFS(metadata?.image);
return { ...nft, image, metadata };
}
} catch (error) {
return nft;
}
return nft;
});

return { ...data, result: formattedResult };
}, [data]);

return { getNFTTokenIds, data: NFTTokenIds, error, isLoading, isFetching };
};