DEV Community

Cover image for React Custom Hooks (useMediaPermission)
sundarbadagala
sundarbadagala

Posted on

React Custom Hooks (useMediaPermission)

INTRO ๐Ÿ”Š

Hello World! ๐Ÿ‘‹
Today's custom hook is useMediaPermission๐Ÿ”ฅ. This post will discuss how to detect media permissions like the camera and microphone of any application.

USAGE ๐Ÿ”Š

While handling media applications like chat and live stream. We have to be aware of whether the user is given camera and microphone permissions or not and have to track whether the user denied or rejected the permissions while using the application. For that purpose, we are creating one custom hook.

๐Ÿ“ŒNote: This hook is mainly focussing on camera and microphone permissions only, not other permissions like geolocation, notification, accelerometer etc...

HOOK 1

import { useEffect } from "react";

export const useMediaPermission = (callback, constraints) => {
  const getPermission = (type) => {
    try {
      navigator.permissions
        .query({ name: type })
        .then((res) => {
          callback({
            name: res.name,
            state: res.state,
          });
          res.onchange = () => {
            callback({
              name: res.name,
              state: res.state,
            });
          };
        })
        .catch((error) => {
          console.log(error.message);
        });
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    if (constraints.length) {
      constraints.map((item) => getPermission(item));
    }
  }, [navigator.permissions]);
};

Enter fullscreen mode Exit fullscreen mode

USE CASE

import React from "react";
import { useMediaPermission } from "./useMediaPermission";

function Inex() {
  const callback = (data) => {
    console.log(data);
  };
  useMediaPermission(callback, ["camera","microphone"]);
  return <div>Inex</div>;
}

export default Inex;

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ŒNote: navigator.permissions.query can't detect camera and microphone permissions in Firefox and Safari. It only supports the browsers Chrome and Edge.
For more information visit this link
For that purpose we have created another hook

HOOK 2

import { useEffect } from "react";

export const useUserMediaPermission = (callback, constraints) => {
  const getPermission = (item) => {
    try {
      navigator.mediaDevices
        .getUserMedia({ [item]: true })
        .then((res) =>
          callback({
            name: item,
            state: res.active,
          })
        )
        .catch((error) =>
          callback({
            name: item,
            state: error.message,
          })
        );
    } catch (error) {
      callback({
        name: item,
        state: error.message,
      });
    }
  };
  useEffect(() => {
    if (constraints.length) {
      constraints.map((item) => getPermission(item));
    }
  }, []);
};
Enter fullscreen mode Exit fullscreen mode

USE CASE

import React from "react";
import { useUserMediaPermission } from "./useUserMediaPermissoin";

function Inex() {
  const callback = (data) => {
    console.log(data);
  };
  useUserMediaPermissio(callback, ["audio", "video"]);
  return <div>Inex</div>;
}

export default Inex;

Enter fullscreen mode Exit fullscreen mode

DIFFERENCE BETWEEN HOOK 1 & 2 (LIMITATIONS)

  • hook 2 will support all browsers but hook 1 will support only Chrome and Edge.
  • If we change the permissions while using the application, hook 1 returns a callback with the latest permission status (whether it accepts or denied/prompted) but this feature won't work in hook 2.
  • If we want to know only the initial status of media permissions, it's better to use hook 2.
  • If we want to know the status of media permissions every time they change while using the application, it's better to user hook 1 (but this works only in Chrome and Edge)
  • Recently I found one NPM package named mic-check. This one is also very helpful to detect the media permissions but unfortunately, this package also detects the permissions only on page load, not every time changes the permissions while using the app.

I hope you people understand the useMediaPermission hook. We will meet with another hook in another post.

Peace ๐Ÿ™‚

Top comments (0)