read clipboard then set value to a variable then store variable in local storage synchronous in javascript

To read clipboard content and store it in local storage synchronously, we need to do the following steps:

  1. Access the clipboard content by using the navigator.clipboard.readText() function.
  2. Store the clipboard content into a variable.
  3. Use setTimeout() function to make sure the local storage operation is executed after the clipboard content is retrieved.
  4. Store the clipboard content into local storage by using the localStorage.setItem() function.

Here's the code:

index.tsx
// Access the clipboard content
navigator.clipboard.readText()
    .then(text => {
        // Store the clipboard content in a variable
        let clipboardContent = text;
      
        // Use setTimeout to make sure the local storage operation is executed after the clipboard content is retrieved
        setTimeout(function(){
            // Store the clipboard content into local storage
            localStorage.setItem('clipboardContent', clipboardContent);
        }, 0);
    })
    .catch(err => {
        console.error('Failed to read clipboard contents: ', err);
    });
582 chars
16 lines

Note: The setTimeout() function is necessary to ensure that the local storage operation is synchronous. Without it, the local storage operation may execute before the clipboard content is retrieved, which will result in the variable being undefined.

gistlibby LogSnag