Tuesday 31 December 2019

Avoid infinite callbacks in Material-UI Avatar Component

Recently I found an issue on my localhost while working on [this open source project](https://github.com/cswbrian/district-councils-dashboard). The page was actually loading extremely slow and I found that there were tons of images being requested again and again.  

The original code is shown as below. It requests ``${homeUrl}/static/images/avatar/${person.uuid}.jpg`` at the beginning, ``${homeUrl}/static/images/avatar/default.png`` is only requested if the main source fails. 

```javascript
 {
            e.target.src = `${homeUrl}/static/images/avatar/default.png`
        },
    }}
/>
```

However, if the fallback image source also fails, it will cause infinite callbacks.

To resolve this issue, it is pretty simple. We just need a state to check if it fails or not.

First, make sure ``useState`` is being imported
```javascript
import { useState } from 'react'
```

Then, define the state with a default value and its setter
```javascript
const [imageLoadError, setImageLoadError] = useState(true)
```

For the first time, we set ``imageLoadError`` to false so that it won't execute again.
```javascript
if (imageLoadError) {
    setImageLoadError(false)
    e.target.src = IMAGE_HOST_URI + '/static/images/avatar/default.png'
}
```

That's it. Then resources won't be requested again and again slowing down your webpage. 
```javascript
import { useState } from 'react'
...
const [imageLoadError, setImageLoadError] = useState(true)
...
 {
            e.target.src = `${homeUrl}/static/images/avatar/default.png`
            if (imageLoadError) {
                setImageLoadError(false)
                e.target.src = IMAGE_HOST_URI + '/static/images/avatar/default.png'
            }
        },
    }}
/>
```

For the demo purpose, I simplified the code. If you are interested, you can see my pull request [here](https://github.com/cswbrian/district-councils-dashboard/pull/99/files).

No comments:

Post a Comment

A Fun Problem - Math

# Problem Statement JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today t...