hoozr
hoozr

Reputation: 463

Handling null in ReactJS

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
               
               
               ....
               )

Upvotes: 1

Views: 817

Answers (4)

Victor
Victor

Reputation: 194

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>

Upvotes: 1

Fatema Tuz Zuhora
Fatema Tuz Zuhora

Reputation: 3716

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>

Upvotes: 0

Sennen Randika
Sennen Randika

Reputation: 1636

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.

Upvotes: 1

hendrixchord
hendrixchord

Reputation: 5434

This will handle undefined and null cases as well.

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

Upvotes: 1

Related Questions