Skip to content

Instantly share code, notes, and snippets.

@townofdon
Last active May 17, 2021 20:19
Show Gist options
  • Save townofdon/97398bfcf6a7c0c3a41706286a1487c8 to your computer and use it in GitHub Desktop.
Save townofdon/97398bfcf6a7c0c3a41706286a1487c8 to your computer and use it in GitHub Desktop.

React Native Hooks

useKeyboardHeight

Calculate the height of the keyboard when it is open.

useRefreshQuery

An apollo useQuery hook with built-in support for ScrollView's RefreshControl

import React from 'react';
import { Keyboard, KeyboardEvent } from 'react-native';
/**
* Determine the current height of the device keyboard.
*/
export function useKeyboardHeight(): React.MutableRefObject<number> {
const keyboardHeight = React.useRef(0);
function onKeyboardWillShow(e: KeyboardEvent): void {
keyboardHeight.current = e.endCoordinates.height;
}
function onKeyboardWillHide(): void {
keyboardHeight.current = 0;
}
React.useEffect(() => {
Keyboard.addListener('keyboardWillShow', onKeyboardWillShow);
Keyboard.addListener('keyboardWillHide', onKeyboardWillHide);
return (): void => {
Keyboard.removeListener('keyboardWillShow', onKeyboardWillShow);
Keyboard.removeListener('keyboardWillHide', onKeyboardWillHide);
};
}, []);
return keyboardHeight;
}
import { DocumentNode, TypedDocumentNode, useQuery } from '@apollo/client';
import { useState } from 'react';
import Bugsnag from '@bugsnag/react-native';
import Toast from 'react-native-toast-message';
import { useLocale } from '../locales/useLocale';
/**
* An apollo useQuery hook with built-in support for ScrollView RefreshControl
*/
export const useRefreshQuery = <R, V>(
QUERY: DocumentNode | TypedDocumentNode<R, V>,
errMsg?: string,
) => {
const text = useLocale();
const [refreshing, setRefreshing] = useState(false);
const query = useQuery<R, V>(QUERY, {
onCompleted: () => {
setRefreshing(false);
},
onError: (err) => {
setRefreshing(false);
Bugsnag.notify(err);
Toast.show({ type: 'error', text2: errMsg || text.error.GENERIC });
},
});
const handleRefresh = async () => {
try {
setRefreshing(true);
await query.refetch();
} catch (err) {
Bugsnag.notify(err);
Toast.show({ type: 'error', text2: errMsg || text.error.GENERIC });
} finally {
setRefreshing(false);
}
};
return {
...query,
handleRefresh,
refreshing,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment