I have this piece of code that is connecting to metamask wallet and sets the account address using useState().
const [currentAccount, setCurrentAccount] = useState("")
const connectWallet = async () => {
try {
if (!ethereum) return alert("Please install MetaMask.")
const accounts = await ethereum.request({ method: "eth_requestAccounts" })
setCurrentAccount(accounts[0])
console.log(accounts)
// TODO:Add conditional statement to check if user has token
navigate("/portfolio")
} catch (error) {
console.log(error)
throw new Error("No ethereum object")
}
}
console.log("current account", currentAccount)
const returnCollection = async (currentAccount) => {
const options = { method: 'GET', headers: { Accept: 'application/json' } };
fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(response => console.log("collection owned by current address", response))
.catch(err => console.error(err));
useEffect(() => {
returnCollection(currentAccount)
})
The console is logging the account but when I try to pass it in the returnCollection call in useEffect() it comes back as undefined.
It seems here, you are doing something like this:
useEffect(() => {
returnCollection(currentAccount)
})
This will run after every rerender or every state change, and also initially when the component is first mounted, when currentAccount is "". Initially, current account is "", so you may not want to get the collection from "". Instead, maybe what you can do is create another state variable for the result of the returnConnection, and set the state variable to the result of the returnConnection, since you typically don't return results from useEffect, unless it's a cleanup function. Also, maybe you can check the state of currentAccount inside of the useEffect to make sure it's not "", before returning the result.