npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-device-permission

v1.1.0

Published

A collection of React hooks for handling device permissions like camera,microphone and etc.

Downloads

92

Readme

npm version
license

React Device Permission 🌍📸🎤

Get microphone, camera, and geolocation(device location) access in a sec

This React hooks library simplifies handling device permissions and recording audio/video streams, as well as accessing geolocation data.

Features ✨

  • 🎥 Record video streams.
  • 🎤 Record audio streams.
  • 🌍 Access device geolocation.
  • 🛠️ Simple and easy-to-use API.

Installation 📦

npm install react-device-permission

Usage 🚀

useRecord Hook

This hook manages recording from the user's camera and/or microphone.

Arguments

| Argument Name | Type | Description | | -------------- | ----------------- | ------------------------------------------------------------------ | | streamType | T_StreamTypeProp| The type of stream to capture ("audio", "video", "audio/video").| | fileName | string | The name of the file to be saved (without extension). |

Returns

| Return Value | Type | Description | |---------------------------|-----------------------|-----------------------------------------------------------------------| | startRecording | () => Promise<void> | Function to start recording. | | stopRecording | () => Promise<void> | Function to stop recording. | | recordSrc | string \| undefined | The URL of the recorded media. | | errors | Error \| undefined | Any errors that occur during recording. | | fileNameWithExtension | string | The complete filename with the correct extension (e.g., "my-video.webm" or "my-audio.ogg").|

Example Usage for useRecord

import React, { useEffect } from 'react';
import { useRecord } from 'react-device-permission';

const App = () => {
  const { startRecording, stopRecording, recordSrc, fileNameWithExtension, errors } = useRecord('video', 'my-video');

  useEffect(() => {
    console.log(errors);
  }, [errors]);

  return (
    <div>
      <button onClick={startRecording}>Start Recording</button>
      <button onClick={stopRecording}>Stop Recording</button>
      {recordSrc && (
        <a href={recordSrc} download={fileNameWithExtension}>
          Download Recording
        </a>
      )}
    </div>
  );
};

export default App;

useGeo Hook

This hook provides a simple interface to access the user's geolocation.

Arguments

| Argument Name | Type | Description | |-------------------|------------------------------|-----------------------------------------------------------------------------------| | geoType | T_GeoType | The type of geolocation request ("watch" for continuous tracking or "current" for one-time capture).| | geoOptions | T_GeoOptions | Options for configuring the geolocation request. | | throttleLimit | number | Optional. Throttle time in milliseconds for "watch" type to limit position updates.|

Returns

| Return Value | Type | Description | |--------------------|----------------------------|------------------------------------------------------------------| | coords | T_GeoPositionCoords | An object containing latitude, longitude, and other position info.| | timestamp | number | Timestamp of the latest geolocation. | | errors | T_GeoErrors | An object containing any errors that occurred during geolocation.| | clearWatchGeo | () => void | Function to clear the watch position when using "watch" mode. |

Types

  • T_GeoOptions: Options for configuring the geolocation request.

    export type T_GeoOptions = {
      enableHighAccuracy?: boolean;  // If true, the device will attempt to use the most accurate location method.
      timeout?: number;              // Maximum time in milliseconds that is allowed to wait for the geolocation response.
      maximumAge?: number;           // Maximum age in milliseconds of a possible cached position that is acceptable to return.
    };
  • T_GeoPositionCoords: Coordinates provided by the geolocation API.

    export type T_GeoPositionCoords = {
      accuracy: number;            // The accuracy of the position in meters.
      altitude: number | null;     // The altitude of the position in meters, or null if not available.
      altitudeAccuracy: number | null; // The accuracy of the altitude in meters, or null if not available.
      heading: number | null;      // The direction the device is moving, in degrees, or null if not available.
      latitude: number;            // The latitude of the position in degrees.
      longitude: number;           // The longitude of the position in degrees.
      speed: number | null;        // The speed at which the device is moving in meters per second, or null if not available.
    };
  • T_GeoPosition: Contains the coordinates and timestamp.

    export type T_GeoPosition = {
      coords: T_GeoPositionCoords; // The coordinates of the position.
      timestamp: number;          // The time at which the position was recorded.
    };
  • T_GeoErrors: Errors that might occur during geolocation.

    export type T_GeoErrors = {
      code?: number;   // The error code, if available.
      message: string; // A description of the error.
    };
  • T_GeoType: Specifies the type of geolocation request.

    export type T_GeoType = 'watch' | 'current';  // 'watch' for continuous updates, 'current' for a single location.

Example Usage for useGeo

import React, { useEffect, useState } from 'react';
import { useGeo } from 'react-device-permission';

const App = () => {
  const { coords, timestamp, errors } = useGeo('watch', { enableHighAccuracy: true, timeout: 5000 }, 1000);

  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    if (coords.latitude !== 0 || coords.longitude !== 0) {
      setIsLoading(false);
    }
  }, [coords]);

  return (
    <div>
      <h1>Geolocation Parameters</h1>
      {isLoading ? (
        <p>Loading geolocation data...</p>
      ) : errors ? (
        <div style={{ color: 'red' }}>
          <p>Error: {errors.message}</p>
        </div>
      ) : (
        <div>
          <p><strong>Latitude:</strong> {coords.latitude}</p>
          <p><strong>Longitude:</strong> {coords.longitude}</p>
          <p><strong>Accuracy:</strong> {coords.accuracy} meters</p>
          <p><strong>Timestamp:</strong> {timestamp}</p>
        </div>
      )}
    </div>
  );
};

export default App;

Other Projects 🛠️

Check out my other projects on GitHub:

  • react-custom-otp: A powerful React component library for adding OTP (One-Time Password) functionality to your project.

Connect with Me 🌐

Feel free to connect with me on LinkedIn:

Contributing 🤝

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

License 📝

This project is licensed under the MIT License.


Note: More hooks will be added to this package in future updates. Stay tuned!