Created
October 13, 2022 00:57
-
-
Save samkingco/c80083ce7eaf2b2d232855dddfd97947 to your computer and use it in GitHub Desktop.
useENS hook with react-query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useAccount } from "wagmi"; | |
| import { useENS } from "./useENS"; | |
| export function MyComponent() { | |
| const { address: connectedAddress } = useAccount(); | |
| const { displayName } = useENS(connectedAddress); | |
| return ( | |
| <> | |
| {connectedAddress ? ( | |
| <p>Connected to: {displayName}</p> | |
| ) : ( | |
| <p>Not connected</p> | |
| )} | |
| </> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useQuery } from "@tanstack/react-query"; | |
| function addressDisplayName(address?: string) { | |
| if (!address) return ""; | |
| const match = address.match( | |
| /^(0x[a-zA-Z0-9]{3})[a-zA-Z0-9]+([a-zA-Z0-9]{4})$/ | |
| ); | |
| if (!match) return address; | |
| return `${match[1]}…${match[2]}`; | |
| } | |
| export function useENS(address?: string) { | |
| const addressLowercase = address && address.toLowerCase(); | |
| const { data, ...ensQuery } = useQuery( | |
| ["ensResolver", addressLowercase], | |
| async () => { | |
| const response = await fetch( | |
| `https://api.ensideas.com/ens/resolve/${addressLowercase}` | |
| ); | |
| if (!response.ok) { | |
| throw new Error("Network response was not ok"); | |
| } | |
| return response.json(); | |
| }, | |
| { | |
| enabled: Boolean(address), | |
| placeholderData: { | |
| address: addressLowercase, | |
| name: null, | |
| displayName: addressDisplayName(addressLowercase), | |
| avatar: null, | |
| }, | |
| } | |
| ); | |
| return { | |
| address: data.address, | |
| name: data.name, | |
| displayName: data.displayName, | |
| avatar: data.avatar, | |
| ensQuery, | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment