Skip to content
Advertisement

Cannot read properties of undefined (reading ‘slice’)

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…

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement