@@ -122,35 +122,34 @@ export function useClickAway(cb) {
122122 return ref ;
123123}
124124
125- export function useCopyToClipboard ( ) {
126- const [ state , setState ] = React . useState ( {
127- error : null ,
128- text : null ,
129- } ) ;
130-
131- const copyToClipboard = React . useCallback ( async ( value ) => {
132- if ( ! navigator ?. clipboard ) {
133- return setState ( {
134- error : new Error ( "Clipboard not supported" ) ,
135- text : null ,
136- } ) ;
137- }
138-
139- const handleSuccess = ( ) => {
140- setState ( {
141- error : null ,
142- text : value ,
143- } ) ;
144- } ;
125+ function oldSchoolCopy ( text ) {
126+ const tempTextArea = document . createElement ( "textarea" ) ;
127+ tempTextArea . value = text ;
128+ document . body . appendChild ( tempTextArea ) ;
129+ tempTextArea . select ( ) ;
130+ document . execCommand ( "copy" ) ;
131+ document . body . removeChild ( tempTextArea ) ;
132+ }
145133
146- const handleFailure = ( e ) => {
147- setState ( {
148- error : e ,
149- text : null ,
150- } ) ;
134+ export function useCopyToClipboard ( ) {
135+ const [ state , setState ] = React . useState ( null ) ;
136+
137+ const copyToClipboard = React . useCallback ( ( value ) => {
138+ const handleCopy = async ( ) => {
139+ try {
140+ if ( navigator ?. clipboard ?. writeText ) {
141+ await navigator . clipboard . writeText ( value ) ;
142+ setState ( value ) ;
143+ } else {
144+ throw new Error ( "writeText not supported" ) ;
145+ }
146+ } catch ( e ) {
147+ oldSchoolCopy ( value ) ;
148+ setState ( value ) ;
149+ }
151150 } ;
152151
153- navigator . clipboard . writeText ( value ) . then ( handleSuccess , handleFailure ) ;
152+ handleCopy ( ) ;
154153 } , [ ] ) ;
155154
156155 return [ state , copyToClipboard ] ;
0 commit comments