NftProvider.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { createContext, useContext, useEffect, useState } from "react"
  2. import { PublicKey } from "@solana/web3.js"
  3. import { useWallet } from "@solana/wallet-adapter-react"
  4. import {
  5. CONNECTION,
  6. } from "@/utils/anchor"
  7. const NftContext = createContext<{
  8. nftState: any | null
  9. }>({
  10. nftState: null,
  11. })
  12. export const useNftState = () => useContext(NftContext)
  13. export const NftProvider = ({
  14. children,
  15. }: {
  16. children: React.ReactNode
  17. }) => {
  18. const { publicKey } = useWallet()
  19. const [nftState, setNftState] = useState<any | null>(null)
  20. useEffect( () => {
  21. setNftState(null)
  22. if (!publicKey) {
  23. return
  24. }
  25. getAssetsByOwner(publicKey);
  26. }, [publicKey]);
  27. async function getAssetsByOwner(ownerAddress: PublicKey) {
  28. const sortBy = {
  29. sortBy: "created",
  30. sortDirection: "asc",
  31. };
  32. const limit = 1000;
  33. const page = 1;
  34. const before = "";
  35. const after = "";
  36. const allAssetsOwned = await CONNECTION.getAssetsByOwner(
  37. ownerAddress.toBase58(),
  38. sortBy,
  39. limit,
  40. page,
  41. before,
  42. after
  43. );
  44. setNftState(allAssetsOwned);
  45. console.log(allAssetsOwned);
  46. }
  47. return (
  48. <NftContext.Provider
  49. value={{
  50. nftState: nftState,
  51. }}
  52. >
  53. {children}
  54. </NftContext.Provider>
  55. )
  56. }