CodeBlock: Clicking on the copy button throws an error and crashes the Flex app
andrucz opened this issue ยท 3 comments
Description
When I click on the CodeBlock copy button, this error is thrown and the Flex v1 app crashes:
React version: 16.13.1 (can't use newer versions with Flex v1)
Link to Reproduction
https://codesandbox.io/p/sandbox/romantic-microservice-zy2py7
Steps to reproduce
No response
Paste Core Version
20.11.0
Browser
Google Chrome 123
Operating System
- macOS
- Windows
- Linux
Additional Information
No response
The issue you're encountering with the CodeBlock copy button causing a crash in your Flex v1 app seems to be related to improper state updates within an onClick
handler. This is likely due to the clipboard.copy(formattedText);
call inside a React.useCallback()
, which then triggers state updates in a way that conflicts with React's expectations for state management, especially under strict mode or concurrent features.
React 18 introduced "Automatic Batching" to improve performance by batching multiple state updates into a single re-render. However, when state updates are performed synchronously inside events like onClick
or lifecycle methods without proper batching, React will throw an error about flushSync
being called from inside a lifecycle method. This indicates that React expects these updates to be batched or wrapped in flushSync
for synchronous updates, to be compatible with the new concurrent features.
To resolve this issue, ensure that any state updates triggered by the copy action are properly batched. This can be achieved using ReactDOM.flushSync()
for synchronous updates or by letting React's event handling naturally batch those updates. Without more details on how clipboard.copy
interacts with the component's state and the state updates management inside useClipboard
, it's challenging to provide a specific solution.
For more information, you can refer to the React documentation on Automatic Batching: React 18 Upgrade Guide - Automatic Batching.
If you need further clarification or have more questions, feel free to ask.
Sources
- packages/paste-core/components/editable-code-block/src/EditableCodeBlockWrapper.tsx
- packages/paste-core/components/code-block/src/CopyButton.tsx
About Dosu
This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.
Help me be more useful! Please leave a ๐ if this is helpful and ๐ if it is irrelevant.
If you want to continue the conversation, start your reply with @dosu-bot.
The recommended fix would have to be applied to the Paste component implementation. Please note that we're using Paste with React 16 due to Twilio Flex v1 constraints.