Code Monkey home page Code Monkey logo

hooks's People

Contributors

adkenyon avatar dabit3 avatar daniakash avatar dependabot[bot] avatar dylanvann avatar faahmad avatar gamal-shaban avatar gertjanreynaert avatar greg-bush avatar hipstersmoothie avatar jozn avatar kanelloc avatar linusu avatar melihberberolu avatar naturalclar avatar ntvinhit avatar petermakowski avatar pistou avatar pvinis avatar reime005 avatar renovate-bot avatar renovate[bot] avatar retyui avatar ronal2do avatar semantic-release-bot avatar thibmaek avatar thinklinux avatar tonyxiao avatar webtaculars avatar zeljkox 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  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

hooks's Issues

Feature request: differentiate landscape-left from landscape-right

Currently, useDeviceOrientation only tells us "landscape" or "portrait". But devices actually have four orientations, not two -- portrait up, portrait down, landscape left, and landscape right. It would be very useful if the hook could support all device orientations.

useKeyboard cause re-render many time

const keyboard = useKeyboard()

this hook cause re-render all component too many on keyboard show and dismiss

after remove it, my app is working properly not re-render on keyboard show and hide

it work fine in android but not work in iOS

could you fixed this hook.

thank you very much

Keyboard height as animated value from useKeyboard

Feature Request

I think it would be nice if useKeyboard could return an Animated.value for the keyboard height.

Why it is needed

Currently, when using keyboardHeight to set e.g. padding it looks very janky when the keyboard is shown or hidden. Exporting an animated value that represents the height could allos the end user to animate the padding as the keyboard appears.

Possible implementation

t.b.d

Code sample

t.b.d.


I need this in a project I'm working on so I will probably submit a pull request as soon as I get time ☺️

REACT-NATIVE-HOOKS USECAMERAROLL

IM TRYING TO USE USECAMERAROLL HOW CAN I USE IT



import { useCameraRoll } from '@react-native-community/hooks'

const [photos, getPhotos, saveToCameraRoll] = useCameraRoll()

{
  photos.map((photo, index) => /* render photos */)
}

<Button title='Get Photos' onPress={() => getPhotos()}>Get Photos</Button>

useDeviceOrientation returns incorrect initial values

Initial values returned by this hook can be incorrect based od how was app started and when hook mounted.

Example:
App is started in portrait, then orientation is chaged to landscape and after that this hook is mounted. It will show that device is in landscape.
Not sure if this is by design or it's a bug.

My current solution looks like this:

function getDimensions() {
  return Dimensions.get("screen");
}

...
function useMyDeviceOrientation() {
...
  const [orientation, setOrientation] = useState({
    portrait: isOrientationPortrait(getDimensions()),
    landscape: isOrientationLandscape(getDimensions()),
  });
...
}

useDimensions is not available on latest version

I am not able to find useDimensions on latest version 3.0.0. Why this was removed? Actually the problem is useWindowDimesions fron RN doesn't send correct width and height when Alert is open on IOS. So can we revert back the removal of useDimensions? I am currently using 2.8.0 in the mean while

useBackHandler Hook ...

When I come to ListScreen, I click the android backbutton, although I can back to the previous screen,

but the Alert defined in RootScreen will always pop up.

Moreover, DetailScreen back directly to RootScreen.

Screen Tree

-RootScreen     
	-ListScreen
		-DetailScreen

root.screen.js

import { useBackHandler } from "@react-native-community/hooks"

const RootScreen = () => {

	const backActionHandler = () => {
        Alert.alert('Wait a moment', 'Are you sure to exit the app?', [
            {
                text: 'go on',
                onPress: () => null,
                style: 'cancel',
            },
            { text: 'OK to exit', onPress: () => BackHandler.exitApp() },
        ]);
        return true;
    };

    useBackHandler(backActionHandler)
  
    return (
      <View>...</View>
    )
  
}

list.screen.js

import { useBackHandler } from "@react-native-community/hooks"

const ListScreen = ({ navigation: { goBack }) => {

	useBackHandler(goBack)
                     
   return (
     <View>...</View>
   )

}

detail.screen.js

const DetailScreen = () => {

	return (
    	<View>...</View>
    )

}

//or

import { useBackHandler } from "@react-native-community/hooks"

const DetailScreen = ({navigation:{goBack}}) => {
	
	useBackHandler(goBack)
  
	return (
    	<View>...</View>
    )

}

Version Info

"@react-native-community/hooks": "^2.6.0",
"@react-navigation/native": "^5.9.2",
"@react-navigation/stack": "^5.14.2",

image
image

Fix `auto` release

Apparently this has broken. auto is not releasing with PR merges anymore. We should fix that.

RN 0.65 Warning for useAppState

EventEmitter.removeListener('appStateDidChange', ...): Method has been deprecated. Please instead use remove() on the subscription returned by EventEmitter.addListener.

Can't use Hook useDimensions

I see many people on YouTube tutorials using this specific hook but I can't import it, did y'all remove it by any chance? And if so how can I replicate the same thing with a different hook?

useKeyboard keyboardShown wrong value

When a component uses useKeyboard() and this component is mounted while the keyboard is open, useKeyboard().keyboardShown returns false.

The background is we have a sticky button at the bottom on multiple screens. This button should not be displayed when the keyboard is open, since it takes away too much space. In one of those screens we only show the button after an text-input is made. At this point the keyboard is open and the button is shown because of the error above.

[Meta] Canaries on PRs?

Description

When the maintainers create a new PR in this repo, a canary release happens. When anyone else creates a PR, it's a fork, so the release doesn't happen.

It would be very useful though. I'm making this issue so we can maybe find a way.

Unable to resolve "@react-native-community/hooks" from "App.js"

New to Development, trying to learn React Native but having an issue when trying to install Hooks. Using Expo Go, which is also showing an issue, says Index.js doesn't exist for hooks. I've already installed Hooks using NPM.

This is my code:

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Image, SafeAreaView, Button, Alert, Dimensions } from 'react-native';
import { useDeviceOrientation } from '@react-native-community/hooks'


export default function App() {
  const orientation = useDeviceOrientation()

  console.log('is orientation portrait: ', orientation.portrait)
  console.log('is orientation landscape: ', orientation.landscape)
  
 
const handleButtonPress = () => {
  Alert.prompt("Title", "This is my message", text => console.log(text))
}

  return (
    <SafeAreaView style={styles.container}>
      <Button
        onPress={handleButtonPress}
        title={"Press me!"}
      />
      <Text>Hello!</Text>
      <StatusBar style="auto" />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f1f1f1',
    alignItems: "center",
    justifyContent: "center",
  },
});

UseInteractionManager clean up on component Unmount

With reference to the documentation of https://reactnative.dev/docs/interactionmanager
The method runAfterInteractions returns a cancellable promise, which has a cancel method, was wondering if this cancel method should be applied on component clean up.

https://github.com/react-native-community/hooks/blob/master/src/useInteractionManager.ts#L8

import {useEffect, useState, useRef} from 'react'
import {InteractionManager} from 'react-native'

export function useInteractionManager() {
  const [complete, updateInteractionStatus] = useState(false)
  const interactionHandler = useRef();
  useEffect(() => {
    interactionHandler.current = InteractionManager.runAfterInteractions(() => {
      updateInteractionStatus(true)
      
      
      
    })
    return () => interactionHandler.current & interactionHandler.current.cancel()
  }, [interactionHandler])
  return complete
}

I cannot load the useAppState hook in my code

Bug

For some reason I get this error when just calling useAppState in my function, that already has many other hooks

Screenshot_20190818-102747

This is the code that runs it, its a child component somewhere, but it runs the code without the useAppState() line. I even added a copy of useAppState in my utils folder and it works.

import React, { useEffect, useState } from 'react';
import { useAppState } from 'react-native-hooks';
import PhoneStatus from '../../containers/phone-status';
import AuthService from '../../services/auth';

import WithoutWallet from './without-wallet';


const onAppFocusChanges = ({ linkingInitialized, setLinkingInitialized }) => {
  if (linkingInitialized) {
    setTimeout(() => {
      setLinkingInitialized(false);
    }, 10000);
  }
};


export default () => {
  const currentAppState = useAppState();
  const [linkingInitialized, setLinkingInitialized] = useState(false);
  
  const phoneStatus = PhoneStatus.useContainer();
  const authService = AuthService.useContainer();

  const { hasWallet } = phoneStatus;
  const { currentUser } = authService;


  useEffect(() => {
    phoneStatus.checkForWallet();
  }, []);


  console.log(hasWallet);

  if (hasWallet) {
    return <WithoutWallet />;
  }
  return <></>;
};

Does this maybe have to do that the react dependency is not a peer dependency stated here: https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

Environment info

React native info output:

info
  React Native Environment Info:
    System:
      OS: macOS 10.14.6
      CPU: (8) x64 Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz
      Memory: 310.77 MB / 16.00 GB
      Shell: 5.3 - /bin/zsh
    Binaries:
      Node: 9.10.0 - ~/.nvm/versions/node/v9.10.0/bin/node
      Yarn: 1.15.2 - ~/.yarn/bin/yarn
      npm: 6.4.0 - ~/.nvm/versions/node/v9.10.0/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.4, macOS 10.14, tvOS 12.4, watchOS 5.3
      Android SDK:
        API Levels: 23, 25, 26, 27, 28
        Build Tools: 23.0.1, 26.0.2, 27.0.3, 28.0.0, 28.0.3
        System Images: android-28 | Google Play Intel x86 Atom
    IDEs:
      Android Studio: 3.1 AI-173.4819257
      Xcode: 10.3/10G8 - /usr/bin/xcodebuild

Version number: "react-native": "^0.59.3"
Which resolves now to "0.59.10"

Describe what you expected to happen:

  1. Expected it not to crash

Reproducible sample code

All the stuff inside that code example is non relateable. And as stated, i copied the code and added a utils/hooks/useAppState and that worked fine. So there is something with loading this lib in.

Height invalid from useWindowDimensions

Hello there,

I am using the height value from useWindowDimensions in Expo.
I am on an iPhone 10 so height is 812, most of the time. But there are sometimes where the hook returns 70 instead of 812.

const { height } = useWindowDimensions();
const { bottom, top } = useSafeAreaInsets();
const bottomOffset = height - bottom - 40;

console.log(`${height} - ${bottom} - 40 = ${bottomOffset}`);

Working result is "812 - 34 - 40 = 738" and sometimes I have "70 - 34 - 40 = -4".

Does somebody know about this?

Thanks.

Is this project still maintained?

Excuse me for the words but I just looked around the hooks and saw so many bad practices in your project (mostly about performance) so I wonder whether you still maintain this project or not.

For example, this hook does resubscribe event every time the component renders. There is a fix here but for maybe some reasons it is merged yet: #38

src/useAppState.ts

import React, { useEffect, useState } from 'react'
import { AppState, AppStateStatus } from 'react-native'

export default function useAppState() {
  const currentState = AppState.currentState
  const [appState, setAppState] = useState(currentState)

  function onChange(newState: AppStateStatus) {
    setAppState(newState)
  }

  useEffect(() => {
    AppState.addEventListener('change', onChange)

    return () => {
      AppState.removeEventListener('change', onChange)
    }
  })

  return appState
}

This hook creates new getPhotos and saveToCameraRoll functions every time the hook is called. It would cause the hook consumer component to rerender unexpectedly.

src/useCameraRoll.ts

export default function useCameraRoll() {
  const [photos, setPhotos] = useState(initialState)

  async function getPhotos(config = defaultConfig) {
    try {
      const photos = await CameraRoll.getPhotos(config)
      setPhotos(photos)
    } catch (err) {
      console.log('error: ', err)
    }
  }

  async function saveToCameraRoll(tag: string, type?: 'photo' | 'video') {
    try {
      await CameraRoll.saveToCameraRoll(tag, type)
    } catch (err) {
      console.log('error saving to camera roll: ', err)
    }
  }

  return [photos, getPhotos, saveToCameraRoll]
}

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @types/jest to v29.5.12
  • chore(deps): update dependency @types/react to v18.2.79
  • chore(deps): update dependency @types/react-native to v0.72.8
  • chore(deps): update dependency react-native to v0.71.18
  • chore(deps): update dependency ts-jest to v29.1.2
  • chore(deps): update dependency @testing-library/react-native to v12.4.5
  • chore(deps): update react monorepo to v18.3.1 (minor) (@types/react, react, react-test-renderer)
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update dependency eslint to v9
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/publish-canary.yml
  • actions/checkout v3
  • actions/setup-node v3
.github/workflows/release.yml
  • actions/checkout v3
  • actions/setup-node v3
npm
package.json
  • @auto-it/all-contributors 10.46.0
  • @auto-it/first-time-contributor 10.46.0
  • @react-native-community/eslint-config 3.2.0
  • @testing-library/react-hooks 8.0.1
  • @testing-library/react-native 12.1.3
  • @types/jest 29.5.3
  • @types/react 18.2.20
  • @types/react-native 0.72.2
  • all-contributors-cli 6.25.1
  • auto 10.46.0
  • eslint 8.41.0
  • eslint-plugin-prettier 4.2.1
  • jest 29.5.0
  • prettier 2.8.8
  • react 18.2.0
  • react-native 0.71.12
  • react-test-renderer 18.2.0
  • ts-jest 29.1.1
  • typescript 5.0.4
  • react >=17.0.2
  • react-native >=0.65

  • Check this box to trigger a request for Renovate to run again on this repository

useDeviceOrientation screen bug

Bug report

Summary

Environment info

react-native info output:

# "react-native": "^0.63.2",

Library version: ^2.6.0

orientation.landscape is always false when change orientation

Can't get error from hooks (e.g. useCameraRoll and useGeolocation)

In current implementation we just ignore errors. In some cases we need access to error.
I guess we need add error in hooks response to avoid breaking changes later.
What do you think about it ?

Example:

import { useGeolocation } from 'react-native-hooks'

const [position, stopObserving, setRNConfiguration, error] = useGeolocation()

console.log('latitude: ', position.coords.latitude)

console.log('error: ', error)

No license

Hi, it seems like no license is attached to this repo yet. This would imply exclusive copyright by default, as stated here.

Assuming this is just an oversight, a license should probably be added to avoid any doubt that this repo is open source.

RN 0.65.1 + useKeyboard() + Fast Refresh = react-native not available on the unmount

I just upgraded to RN 0.65.1 and didn't have this problem before but this is also the only library I'm having this issue with.

When I change something in the file and Fast Refresh reloads the file I get the following error where it appears that upon reload react-native is no longer loaded on the unmount in node_modules/@react-native-community/hooks/lib/useKeyboard.js.

Screen Shot 2021-08-26 at 11 52 53

TypeScript Support

There's currently no index.d.ts file or corresponding @types/react-native-hooks available.

useKeyboard does not respect iPad floating keyboard

Firstly thank you for the fine work!

TIL there is a thing called "floating keyboard" for iPad. You can enable it by pinching on the keyboard on iPad and disable it by un-pinching(?).

image

keyboardShown and keyboardHeight seem to misbehave when this is active and when you dismiss it.

Using the following code for the scenarios below:

  const { keyboardShown, keyboardHeight } = useKeyboard();
  console.log('keyboardHeight: ', keyboardHeight);
  console.log('keyboardShown: ', keyboardShown);

When Floating Keyboard is open from the start (maybe you already set this in another app), it logs:

 LOG  keyboardHeight:  0
 LOG  keyboardShown:  false

And then when you swipe to remove the floating keyboard and replace it with the regular keyboard, it logs (this is good):

 LOG  keyboardHeight:  337
 LOG  keyboardShown:  true

And then, pinch to enable the floating keyboard again, and it logs (this is bad):

 LOG  keyboardHeight:  337
 LOG  keyboardShown:  false

It seems like at the very least, keyboardHeight should be set to 0 on the last scenario. That way you can inform the your KeyboardAvoidingView to be enabled={false}. That is how I discovered the issue.

There is a decent answer here about detecting the floating keyboard. Perhaps some additional fields could be added to the hook to make it more useful.

Make AppStateStatus a enum and export it

AppStateStatus should be a enum and export, it's better for stability, using with the useAppState hook and avoids having to manually create enums for app states which could potentially change in the future leading to more issues.

If this is accepted I can create a PR for it.

Can't install through npm

Question

image
Trying to use the useDimensions library from @react-native-community/hooks but I can't install it. Any help?

Deprecated API

Do you have any ideas on how to support the next hooks as they are deprecated or removed?

Shell we will mark them as @deprecated too (using comments), or add info in the README file?

useCameraRoll

CameraRoll was removed in React Native 0.61.x

image

useClipboard

Clipboard marker as deprecated, but not deleted yet (see master)

image

null is not an object (evaluating e.endCoordinates)

Bug

I use useKeyboard hook, and when the keyboard is closing I got an error null is not an object (evaluating e.endCoordinates).

Screenshot_20190827-124808

Environment info

React native info output:

info
  React Native Environment Info:
    System:
      OS: Windows 10
      CPU: (4) x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
      Memory: 5.21 GB / 15.88 GB
    Binaries:
      Yarn: 1.16.0 - C:\Users\David\Projects\WI\personalized-nutrition-app\node_modules\.bin\yarn.CMD
      npm: 6.5.0 - C:\Program Files\nodejs\npm.CMD
    IDEs:
      Android Studio: Version  3.0.0.0 AI-171.4408382

Done in 3.07s.

Library version: 0.9.0

Steps To Reproduce

  1. Add useKeyboard. show a text only if the keyboard is close.
  2. Open the keyboard.
  3. After you close the keyboard you got the error and the text still hidden.

Describe what you expected to happen:

  1. I expect that the text will appear again.

Reproducible sample code

import { useKeyboard } from 'react-native-hooks'
...
const { isKeyboardShow } = useKeyboard()
return (

{!isKeyboardShow && Test useKeyboard}

</View>

)

Possible fix:

Instead of writing endCoordinates: e.endCoordinates, write endCoordinates: e ? e.endCoordinates : null,

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.