Giter VIP home page Giter VIP logo

react-hooks's Introduction


Capacitor React Hooks

A set of hooks to help Capacitor developers use native Capacitor APIs.


Maintainers

Maintainer GitHub Social
Ely Lucas elylucas @elylucas

These docs are for Capacitor 3 plugins. For docs that target v2 plugins, see the capv2 branch.

Getting Started

To start using Capacitor Hooks in your app, you install the React Hook package along with the Capacitor plugin you want to use. Here is an example of using the Storage plugin along with it's React hook:

# Install the Capacitor Plugin
npm install @capacitor/storage 
# And then the React hook package:
npm install @capacitor-community/storage-react

Import the hooks:

import { useStorage } from '@capacitor-community/storage-react'

Then use the hooks in your app:

const [value, setValue] = useStorage('mykey');

Feature Detection

While Capacitor allows you to write to one API across several platforms, not all features are supported on all platforms. It is encouraged to check if the feature you intend to use is available before using it to avoid any runtime errors.

Each of the hook plugin paths exports an availableFeatures object, which contains a list features for that plugin. If the feature is supported for the current platform the app is running on, that feature will be true:

const { useStorageItem, availableFeatures } = `@capacitor-community/storage-react`;
const [value, setValue] = useStorage('mykey');
...
if(availableFeatures.useStorage) {
  // Storage is available, feel free to use it!
  setValue('cake');
}

Upgrading from Capacitor 2 React Hooks

In Capacitor 3, all the plugins were separated into their own packages. Likewise, the new React hooks plugins were also put into their own package, so you will need to install the hook for each plugin you use.

Any deprecated API'S from Capacitor 2 to 3 were also removed and updated, so you might need to make some modifications to account for API changes. See the Capacitor Plugin API for to learn more.

Hook Usage

@capacitor/app Hooks

Installation:

npm install @capacitor-community/app-react

Usage:

import { useAppState, useAppUrlOpen, useLaunchUrl, availableFeatures } from '@capacitor-community/app-react';

useAppState provides access to App status information, such as whether the app is active or inactive. This value will update dynamically.

const {state} = useAppState();

useLaunchUrl

useLaunchUrl provides the URL the app was initially launched with. If you'd like to track future inbound URL events, use useAppUrlOpen below instead.

const { launchUrl } = useLaunchUrl();

useAppUrlOpen

useAppUrlOpen provides the most recent URL used to activate the app. For example, if the user followed a link in another app that opened your app.

const { appUrlOpen } = useAppUrlOpen();

See the App Capacitor Plugin docs for more info on the plugin API.

@capcitor/browser Hooks

Installation:

npm install @capacitor-community/browser-react

Usage:

import { useClose, useOpen, availableFeatures } from '@capacitor-community/browser-react';

useOpen, useClose provides a way to launch, and close an in-app browser for external content:

// Open url in browser
const { open } = useOpen();

open({ url: 'http://ionicframework.com' });

// Close url in browser
const { close } = useClose();
useClose();

See the Browser Capacitor Plugin docs for more info on the plugin API.

@capacitor/camera Hooks

Installation:

npm install @capacitor-community/camera-react

Usage:

import { useCamera, availableFeatures } from '@capacitor-community/camera-react';

useCamera provides a way to take a photo:

const { photo, getPhoto } = useCamera();
const triggerCamera = useCallback(async () => {
  getPhoto({
      quality: 100,
      allowEditing: false,
      resultType: CameraResultType.DataUrl
    })
}, [getPhoto]);

<div>{photo && <img alt="" src={photo.dataUrl} />}</div>

See the Camera Capacitor Plugin docs for more info on the plugin API.

Clipboard Hooks

Installation:

npm install @capacitor-community/clipboard-react

Usage:

import { useClipboard, availableFeatures } from '@capacitor-community/clipboard-react';

useClipboard reads and writes clipboard data:

const { value, getValue, setValue } = useClipboard();

const paste = useCallback(async () => {
  await setValue('http://ionicframework.com/);
}, [setValue]);

const copy = useCallback(async () => {
  getValue(); 
}, [getValue])

See the Clipboard Capacitor Plugin docs for more info on the plugin API.

Device Hooks

Installation:

npm install @capacitor-community/device-react

Usage:

import { useGetInfo, useGetLanguageCode, availableFeatures } from '@capacitor-community/device-react';

useGetInfo, useGetLanguageCode gives access to device information and device language settings:

const { info } = useGetInfo();
const { languageCode } = useGetLanguageCode();

See the Device Capacitor Plugin docs for more info on the plugin API.

Filesystem Hooks

Installation:

npm install @capacitor-community/filesystem-react

Usage:

import { useFilesystem, base64FromPath, availableFeatures } from '@capacitor-community/filesystem-react';

useFilesystem returns back common methods to gain access to file system apis.

const { readFile } = useFilesystem();

const file = await readFile({
  path: filepath,
  directory: FilesystemDirectory.Data
});

base64FromPath is a helper method that will take in a path to a file and return back the base64 encoded representation of that file.

See the Filesystem Capacitor Plugin docs for more info on the plugin API.

const base64String = await base64FromPath(path);

Geolocation Hooks

Installation:

npm install @capacitor-community/geolocation-react

Usage:

import { useCurrentPosition, useWatchPosition, availableFeatures } from '@capacitor-community/geolocation-react';

useCurrentPosition returns a single geolocation position using the Geolocation API in Capacitor. The position can be manually updated by calling getPosition:

const { currentPosition, getPosition } = useCurrentPosition();

const handleRefreshPosition = () => {
  getPosition();
}

useWatchPosition tracks a geolocation position using the watchPosition in the Geolocation API in Capacitor. The location will automatically begin updating, and you can use the clearWatch and startWatch methods to manually stop and restart the watch.

const { currentPosition, startWatch, clearWatch } = useWatchPosition();

See the Geolocation Capacitor Plugin docs for more info on the plugin API.

Keyboard Hooks

Installation:

npm install @capacitor-community/keyboard-react

Usage:

import { useKeyboardState } from '@capacitor-community/keyboard';

useKeyboard returns whether or not the on-screen keyboard is shown as well as an approximation of the keyboard height in pixels.

const { isOpen, keyboardHeight } = useKeyboard();
// Use keyboardHeight to translate an input that would otherwise be hidden by the keyboard

See the Keyboard Capacitor Plugin docs for more info on the plugin API.

Network Hooks

Installation:

npm install @capacitor-community/network-react

Usage:

import { useStatus, availableFeatures } from '@capacitor-community/network-react';

useStatus monitors network status and information:

 const { networkStatus } = useStatus();

See the Network Capacitor Plugin docs for more info on the plugin API.

ScreenReader Hooks

Installation:

npm install @capacitor-community/screen-reader-react

Usage:

import { useIsScreenReaderEnabled, useSpeak, availableFeatures } from '@capacitor-community/screen-reader-react';

useIsScreenReaderEnabled provides access to detecting and responding to a screen reading device or OS setting being enabled:

const {isScreenReaderEnabled} = useIsScreenReaderEnabled();

useSpeak activates a text-to-speech engine (if available) to read spoken text.

const { speak } = useSpeak();
speak({value: textToSpeak})

See the ScreenReader Capacitor Plugin docs for more info on the plugin API.

Storage Hooks

Installation:

npm install @capacitor-community/storage-react

Usage:

import { useStorage, useStorageItem, availableFeatures } from '@capacitor-community/storage-react';

useStorage provides access to Capacitor's storage engine. There is also a helper called useStorageItem which makes managing a single item easy if you don't need to access the full Storage API (see below)

const { get, set, remove, getKeys, clear } = useStorage();
useEffect(() => {
  async function example() {
    const value = await get('name');
    await set('name', 'Max');
    await remove('name');
    const allKeys = await getKeys();
    await clear();
  }
}, [ get, set, remove, keys, clear ]);

useStorageItem

useStorageItem tracks a single item and provides a nice way to read and write that item:

const [ name , setName ] = useStorageItem('name', 'Max');

// Example:
const updateName = useCallback((n) => {
  setName(n);
}, [ setName ]);

useStorageItem will use the initial value already in storage, or the one provided if there is no existing value.

See the Storage Capacitor Plugin docs for more info on the plugin API.

Other Hooks

This is an evolving project and not all of the Capacitor Plugins are supported yet. If there is one you need, feel free top open an issue for it, or better yet, submit a PR!

react-hooks's People

Contributors

bipoza avatar eliancordoba avatar elylucas avatar leandrogehlen avatar liamdebeasi avatar m165437 avatar macbookandrew avatar michaeltheobald avatar mlynch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-hooks's Issues

Web - Notification API Check feature

Is your feature request related to a problem? Please describe.
Notification is not supported so app crashes, need to find a way to stop using hook if Notification is not supported in web-view

Describe the solution you'd like
Support to check Notification feature is supportable or not.

Describe alternatives you've considered
Skip to load the custom hook

Additional context

Impossible to install on React 17

Describe the bug
With the latest (at this date) React 17 and NPM with lock files v2, it is impossible to install without forcing dependencies:

λ npm install @capacitor-community/react-hooks
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.6" from @capacitor-community/[email protected]
npm ERR! node_modules/@capacitor-community/react-hooks
npm ERR!   @capacitor-community/react-hooks@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

To Reproduce
Steps to reproduce the behavior:

λ npm install -g @ionic/cli
λ ionic start myApp blank --type=react
λ cd myApp
λ npm install @capacitor-community/react-hooks

Why does useFilesystem Exists?

Why do I need this hook? Why are you not satisfied with accessing these functions directly?
All functions from this hook are static and have no initialization stage, functions have no state, available features do not change. These are literally static functions wrapped in useCallback, which are already memoized and never change.

And this is the only hook that is described in the documentation

Capacitor v4 Support

Describe the bug
When I run npm install with @capacitor-community/storage-react and @capacitor/[email protected] in my package.json, I run in to a peer dependency error because @capacitor-community/storage-react requires @capacitor/core@">=3.0.0". If the hooks are compatible, we should simply update the peerDependencies list in each to add capacitor v4.

To Reproduce
Steps to reproduce the behavior:

  1. set up a capacitor v4 project
  2. npm i @capacitor-community/storage-react
  3. See the peer dependency error in console

Expected behavior
The package should install without errors.

Screenshots
image

Desktop (please complete the following information):

  • OS: Mac OS Ventura
  • Browser N/A

Additional context
npm version 8+

Test with Jest: SyntaxError: Unexpected token 'export'

Describe the bug
Test suite with react-hooks fails with

Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

(...)/node_modules/@capacitor-community/react-hooks/geolocation/index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){export * from './useGeolocation';

To Reproduce
Steps to reproduce the behavior:

  1. Create React app with create-react-app
  2. Create custom hook using useGeolocation
  3. Create test for custom hook
  4. Run npm test
  5. See error

Expected behavior
Test does not fail with compile error

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS
  • Browser terminal
  • Version 11.2.2

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Bug: Storage API always returns string on web

Hi, the following code always returns a string instead of an object after a page reload:

const [ myObj , setMyObj ] = useStorageItem<object>('myobj');

const set = () => {
  setMyObj({
    'key1': 'value1',
    'key2': 'value2',
  });
};

// After the set function is calledmyObj is of type object, but after a page reload myObj is of type string
console.log(myObj);

I think it's caused by the following line https://github.com/ionic-team/ionic-react-hooks/blob/76745d1b3a0b4c62949dd6095ede3cbb4843c9ab/src/storage/useStorage.ts#L87 because on the web the type of result.value is always string. Which is because of the implementation of the storage API for the web, where localStorage.getItem() always returns a string or null for the value key: https://github.com/ionic-team/capacitor/blob/f08e4a4f3cff1eedca3ca7292da7892ab2de5806/core/src/web/storage.ts#L21

I fixed it for me the following way:

-          setStoredValue(typeof result.value === 'string' ? result.value : JSON.parse(result.value!));
          
+          try {
+            const parsedValue = JSON.parse(result.value!);
+            setStoredValue(parsedValue);
+          } catch (err) {
+            setStoredValue(result.value);
+          }

If you want I can submit a PR with the change, but I think there should be a better solution than using try and catch.

Error Loading into CodeSandbox.io

Error: Could not fetch dependencies, please try again in a couple seconds: Something
went wrong while packaging the dependency @ionic/[email protected]: ENOENT: 
no such file or directory, 
scandir '/tmp/2309092033/node_modules/@ionic/react-hooks/dist/esm'

Can we add a new `Provider` component with hook?

Now I'm contributing to the Stripe plugin for Capacitor.
https://github.com/capacitor-community/stripe

And I would like to publish new useful utils for this plugin to React developers.
But for now, I'm using a Provider component like this.
https://github.com/capacitor-community/stripe/blob/demo/react/demo/react/src/fixtures/Provider.tsx

Can we add these types of files into your project as @capacitor-community/stripe-react?
Or should we make only React hook?
Thanks!

Bug: Failed to parse source map from on Ionic 6 with react-scripts@5

Describe the bug
After upgrading to react-script@5 the following error appears in the console: Failed to parse source map from

The problem:
The problem here is that Ionic React 6 uses react-scripts@5. This new version of react-scripts has sourcemap parsing enabled and will log a warning when no sourcemaps are found for a library. This did not happen in Ionic React 5 as that version required react-scripts@4 which did not have sourcemap parsing.

To Reproduce
Steps to reproduce the behavior:

$ npm install -g @ionic/cli
$ ionic start myApp blank --type=react
$ cd myApp
$ npm install @capacitor/browser
$ npm install @capacitor-community/browser-react
$ ionic serve

Screenshots
capacitor-react-hooks-sourcemaps

Possible solution:

The same thing happened to me with a library we created to display images with pinch-to-zoom in Ionic React.
https://github.com/codesyntax/ionic-react-photo-viewer

In my case I have used rollupjs as a module builder, and adding the sourcemaps in the configuration works perfectly.
Example: https://github.com/codesyntax/ionic-react-photo-viewer/pull/14/files

ERESOLVE unable to resolve dependency tree

Describe the bug
unable to resolve dependency tree once we upgraded to latest version of capacitor
To Reproduce
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @capacitor/[email protected]
npm ERR! node_modules/@capacitor/core
npm ERR! @capacitor/core@"^3.2.3" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @capacitor/core@"~1.3.0" from @ionic/[email protected]
npm ERR! node_modules/@ionic/react-hooks
npm ERR! @ionic/react-hooks@"0.0.8" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Expected behavior
Should install

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.