Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle undefined mediaDevices #830

Merged
merged 3 commits into from Feb 4, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 11 additions & 10 deletions src/useMediaDevices.ts
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
@@ -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) {
xobotyi marked this conversation as resolved.
Show resolved Hide resolved
handleError(error);
}
};

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