2020-06-15 17:13:12 +03:00
|
|
|
import { useEffect, useState } from 'react'
|
|
|
|
|
|
|
|
/**
|
2020-08-07 02:18:43 +03:00
|
|
|
* Returns the last value of type T that passes a filter function
|
2020-06-15 17:13:12 +03:00
|
|
|
* @param value changing value
|
2020-08-07 02:18:43 +03:00
|
|
|
* @param filterFn function that determines whether a given value should be considered for the last value
|
2020-06-15 17:13:12 +03:00
|
|
|
*/
|
2020-08-07 02:18:43 +03:00
|
|
|
export default function useLast<T>(
|
|
|
|
value: T | undefined | null,
|
|
|
|
filterFn?: (value: T | null | undefined) => boolean
|
|
|
|
): T | null | undefined {
|
|
|
|
const [last, setLast] = useState<T | null | undefined>(filterFn && filterFn(value) ? value : undefined)
|
2020-06-15 17:13:12 +03:00
|
|
|
useEffect(() => {
|
2020-08-07 02:18:43 +03:00
|
|
|
setLast(last => {
|
|
|
|
const shouldUse: boolean = filterFn ? filterFn(value) : true
|
|
|
|
if (shouldUse) return value
|
|
|
|
return last
|
|
|
|
})
|
|
|
|
}, [filterFn, value])
|
2020-06-15 17:13:12 +03:00
|
|
|
return last
|
|
|
|
}
|
2020-08-07 02:18:43 +03:00
|
|
|
|
|
|
|
function isDefined<T>(x: T | null | undefined): x is T {
|
|
|
|
return x !== null && x !== undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the last truthy value of type T
|
|
|
|
* @param value changing value
|
|
|
|
*/
|
|
|
|
export function useLastTruthy<T>(value: T | undefined | null): T | null | undefined {
|
|
|
|
return useLast(value, isDefined)
|
|
|
|
}
|