Skip to content

Instantly share code, notes, and snippets.

@Alina-chan
Created October 20, 2023 16:18
Show Gist options
  • Save Alina-chan/f5830572a9ed3af3e655713308e6e74a to your computer and use it in GitHub Desktop.
Save Alina-chan/f5830572a9ed3af3e655713308e6e74a to your computer and use it in GitHub Desktop.
A hook in React that returns owned objects by given type.
import { JsonRpcProvider } from "@mysten/sui.js";
export function useGetObjects(provider: JsonRpcProvider) {
const getObjectsByType = (
address: string | undefined,
type: string,
nextCursor: string = ''
): Promise<any> => {
// return an empty array for non-address.
if (!address) return Promise.resolve([]);
let objectsArray: any[] = [];
let getObjectsQuery = {
filter: { StructType: type },
owner: address,
options: {
showContent: true,
showOwner: true,
showType: true
},
};
if (nextCursor) Object.assign(getObjectsQuery, { cursor: nextCursor });
return provider.getOwnedObjects(getObjectsQuery).then(async (res) => {
let objectsArray = res.data.map((item) => item.data); // Add current page's data to array
let nextPageData: any[] = [];
if (res.hasNextPage && typeof res?.nextCursor === 'string') {
nextPageData = await getObjectsByType(address, type, res.nextCursor); // You should also pass the type along with the nextCursor
}
return objectsArray.concat(nextPageData);
});
};
return {
getObjectsByType,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment