Search code examples
javascriptreactjscharat

How to avoid TypeError: Cannot read property 'charAt' of undefined when the json input is not available?


I have an avatar that shows the first letter of the user's first name. The list of user name comes when the API call. If the API call not happened TypeError: Cannot read property 'charAt' of undefined error coming as there is no in put json. My react code as follows.

<Avatar
                    style={{ color: "#ffffff", backgroundColor: "#5e206e" }}
                  >
                    {item.user != null ? item.user.charAt(0) : "UU"}
                  </Avatar>

Solution

  • User can still be undefined and throw error. I would also check first for user.

    I suggest to use Optional Chaining introduced in ES2020.

    <Avatar style={{ color: "#ffffff", backgroundColor: "#5e206e" }}>
        {item?.user ? item.user.charAt(0) : "UU"}
    </Avatar>