Skip to content

Commit

Permalink
fix: library crashes when localStorage is not callable (#342)
Browse files Browse the repository at this point in the history
Currently, we're checking for localStorage's presence but not its
actual usability. In some scenarios, browsers can disallow
`localStorage` to be called upon and in such cases, the library will hard
crash.

In this change, I added a catch statement to intercept these errors and
return an empty string when `localStorage` cannot be called upon.

- [X] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)

- [X] I have used ESLint & Prettier to follow the code style of this project.
- [X] I have updated the documentation accordingly.
- [X] I have added tests to cover my changes.
- [X] All new and existing tests passed.
  • Loading branch information
Yuri Levenhagen-Serabion authored Jun 16, 2020
1 parent edbe061 commit 82bf01c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/components/IntlTelInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -522,13 +522,19 @@ class IntlTelInput extends Component {
}
}

loadAutoCountry = () => {
// check for localStorage
const lsAutoCountry =
window.localStorage !== undefined
loadCountryFromLocalStorage = () => {
try {
return window.localStorage !== undefined
? window.localStorage.getItem('itiAutoCountry')
: ''
} catch (e) {
return ''
}
}

loadAutoCountry = () => {
// check for localStorage
const lsAutoCountry = this.loadCountryFromLocalStorage()
if (lsAutoCountry) {
this.autoCountry = lsAutoCountry
}
Expand Down
19 changes: 19 additions & 0 deletions src/components/__tests__/FlagDropDown.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,25 @@ describe('FlagDropDown', function() {
})
})

it('should fallback to US when localStorage is not available', async () => {
const mockedLocalStorage = window.localStorage
// This will cause calls to localStorage.getItem() to throw
window.localStorage = {}

this.params = {
...this.params,
defaultCountry: 'auto',
}
const subject = await this.makeSubject()

subject.instance().utilsScriptDeferred.then(() => {
expect(subject.state().countryCode).toBe('us')
window.localStorage.clear()
})

window.localStorage = mockedLocalStorage
})

it('should has .separate-dial-code class when with separateDialCode = true', () => {
this.params = {
...this.params,
Expand Down

0 comments on commit 82bf01c

Please sign in to comment.