( getItem: () => T | undefined, action: (item: T | undefined) => void, sendInitialUndefined = true )
| 2 | |
| 3 | /** Call a function when the id of the item changes */ |
| 4 | export function useChanged<T extends { id: string }>( |
| 5 | getItem: () => T | undefined, |
| 6 | action: (item: T | undefined) => void, |
| 7 | sendInitialUndefined = true |
| 8 | ) { |
| 9 | const previousItemId = useRef<string | undefined>(); |
| 10 | const item = getItem(); |
| 11 | |
| 12 | //when the value changes, call the action |
| 13 | useEffect(() => { |
| 14 | if (previousItemId.current !== item?.id) { |
| 15 | action(item); |
| 16 | } |
| 17 | |
| 18 | previousItemId.current = item?.id; |
| 19 | }, [item]); |
| 20 | |
| 21 | //if sendInitialUndefined is true, call the action when the component first renders |
| 22 | useEffect(() => { |
| 23 | if (item !== undefined || sendInitialUndefined === false) return; |
| 24 | action(item); |
| 25 | }, []); |
| 26 | } |
no test coverage detected
searching dependent graphs…