Home > Software engineering >  Cannot read properties of undefined (reading 'slice')
Cannot read properties of undefined (reading 'slice')

Time:04-25

I can't figure out the problem with the code as I have even matched it with the source code provided by the git user and it is same, but still showing error So below is the error:- error

Below is the code for shortenAddress component:-

 export const shortenAddress = (address) => `${address.slice(0, 5)}...${address.slice(address.length - 4)}`;

Below is the code of the Welcome component

        <p className="text-white font-light te-xt-sm">{shortenAddress(currentAccount) }</p>

Please,can someone tell the answer to this question of mine...

CodePudding user response:

The issue is because, when you wont get address then address is undefined and not an array.

What you can do is, check address exists like

export const shortenAddress = (address) => {
  if(address.length) {
    return `${address.slice(0, 5)}...${address.slice(address.length - 4)}`
  }
  return address
}

OR you can also optional chaining ? operator:

export const shortenAddress = (address) => `${address?.slice(0, 5)}...${address?.slice(address.length - 4)}`;

Let me know, if you feel any issue.

  • Related