Calculate the height of the keyboard when it is open.
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, | |
}; | |
}; |