Skip to content

Commit

Permalink
fix: handle undefined mediaDevices
Browse files Browse the repository at this point in the history
  • Loading branch information
OBe95 committed Dec 11, 2019
1 parent a48f960 commit 6f68437
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
21 changes: 11 additions & 10 deletions src/useMediaDevices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,17 @@ const useMediaDevices = () => {
let mounted = true;

const onChange = () => {
navigator.mediaDevices
.enumerateDevices()
.then(devices => {
if (mounted) {
setState({
devices: devices.map(({ deviceId, groupId, kind, label }) => ({ deviceId, groupId, kind, label })),
});
}
})
.catch(noop);
navigator.mediaDevices &&
navigator.mediaDevices
.enumerateDevices()
.then(devices => {
if (mounted) {
setState({
devices: devices.map(({ deviceId, groupId, kind, label }) => ({ deviceId, groupId, kind, label })),
});
}
})
.catch(noop);
};

on(navigator.mediaDevices, 'devicechange', onChange);
Expand Down
22 changes: 20 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
export const isClient = typeof window === 'object';

export const on = (obj: any, ...args: any[]) => obj.addEventListener(...args);
export const on = (obj: any, ...args: any[]) => {
try {
obj.addEventListener(...args);
} catch (error) {
handleError(error);
}
};

export const off = (obj: any, ...args: any[]) => obj.removeEventListener(...args);
export const off = (obj: any, ...args: any[]) => {
try {
obj.removeEventListener(...args);
} catch (error) {
handleError(error);
}
};

const handleError = (error: any) => {
if (process.env.NODE_ENV !== 'production') {
console.error(error);
}
};

0 comments on commit 6f68437

Please sign in to comment.