Skip to content

Commit 068481f

Browse files
authored
Merge pull request #76 from react-native-community/global-clipboard-listener
Use a global list of clipboard listeners
2 parents edc8187 + fa54b7d commit 068481f

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/useClipboard.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,30 @@
11
import {useEffect, useState} from 'react'
22
import {Clipboard} from 'react-native'
33

4+
type Listener = (content: string) => void
5+
const listeners = new Set<Listener>()
6+
7+
function setString(content: string) {
8+
Clipboard.setString(content)
9+
listeners.forEach(listener => listener(content))
10+
}
11+
412
export default function useClipBoard() {
513
const [data, updateClipboardData] = useState('')
614

7-
async function updateClipboard() {
8-
const content = await Clipboard.getString()
9-
updateClipboardData(content)
10-
}
11-
15+
// Get initial data
1216
useEffect(() => {
13-
updateClipboard()
17+
Clipboard.getString().then(updateClipboardData)
1418
}, [])
1519

16-
function setString(content: string) {
17-
Clipboard.setString(content)
18-
updateClipboardData(content)
19-
}
20+
// Listen for updates
21+
useEffect(() => {
22+
listeners.add(updateClipboardData)
23+
24+
return () => {
25+
listeners.delete(updateClipboardData)
26+
}
27+
}, [])
2028

2129
return [data, setString]
2230
}

0 commit comments

Comments
 (0)