1

I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> { 
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(
<tbody>
           {users.map(user=> 
               <tr key = {user.id}> 
               <td>{user.id}</td>
               <td>{user.userName}</td>
               <td>{user.fullName}</td>
               <td>{user.department.name}</td>  <---- here i am getting crash when department is null
               
               
               ....
               )

1
  • Check this Commented May 31, 2020 at 15:12

4 Answers 4

1

This is a JavaScript error. If you try to access a property in an object which is null or undefined, you'll get a Type Error. The solution is to validate the data before showing it like this:

<td>{user.department && user.department.name}</td>
Sign up to request clarification or add additional context in comments.

1 Comment

So tricky JS. When we need firstly check the whole .department and only then use data from variable. Thanks!
1

This will handle undefined and null cases as well.

<td>{user.department && user.department.name || ''}</td>  

Comments

1

Please correct your ternary as follows...

{user.department ? user.department.name : ''}

Here, it only checks for user.department.name if and only if user.department is NOT null.

Comments

0

You need to just validate is the property of the object is undefined or not.

<td>
    {user.department ? user.department.name ? user.department.name :null :null}
</td>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.