Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Why is the account address from metamask coming back as undefined after storing it in useState()

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!