Home > Blockchain >  React ('url' )undefined properties cannot be read
React ('url' )undefined properties cannot be read

Time:06-26

I have access the state from the redux const { isauthenticated, user } = useSelector((state) => state.user);

but as you can see in the code below

    <div className="container-fluid upnavcon">
            <span className="navbar-brand fs-1 gwen">Gadget Zone</span>
            {isauthenticated ? (
              <div className="buttonbox">
                <Link className="upnavbtns" to="/LogSign">
                  Login / Signup
                </Link>
              </div>
            ) : (
              <>
              <SpeedDial
                ariaLabel="SpeedDial tooltip example"
                onClose={() => setOpen(false)}
                onOpen={() => setOpen(true)}
                open={open}
                direction="down"
                icon={
                  <img
                    className="speedDialIcon"
                    src={`${user.avatar.url?user.avatar.url:"/logo192.png"}`}
                    alt="pic"
                    />
                }
                >
                <SpeedDialAction icon={<DashboardIcon/>} tooltipTitle="DAshboard"/>
                <SpeedDialAction icon={<DashboardIcon/>} tooltipTitle="DAshboard"/>
              </SpeedDial>
                </>
            )}
          </div>

that if the user isautheticated then I am showing something else the problem is that Cannot read properties of undefined (reading 'url') and at the very end of the error it says

Consider adding an error boundary to your tree to customize error handling behavior.

My state on reload is loading:false, isauthenticated:true and after 2 secs it is loading:false, isauthenticated:true,user{...}

CodePudding user response:

Like Hunter McMillen added in the comments, it looks like user.avatar is undefined.

so when you create the ternary expression:

user.avatar.url ? user.avatar.url : "/logo192.png"

It's failing at user.avatar.url because user.avatar is undefined.

You can fix this with optional chaining, as follows:

user.avatar?.url ? user.avatar.url : "/logo192.png"

Edit: As Ahmad Faraz said in the comments, you can further simplify this to user.avatar?.url || "/logo192.png", no need to use a ternary expression.

CodePudding user response:

Looks like user.avatar can be undefined. To fix the error just add a check on that line:

src={`${user.avatar?.url ? user.avatar.url : "/logo192.png"}`}

CodePudding user response:

How are you storing your state? You could try to use ternary when you're calling it, it is not the right way to fix it but you could try this.

const { isauthenticated, user } = useSelector((state) => state?.user);

  • Related