Skip to content

Commit 9add4ed

Browse files
committed
fix: handle an error when highlighting an unmount component, occurs when navigating between tabs
1 parent 7cad06e commit 9add4ed

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

packages/ui/src/components/Highlight/Highlight.tsx

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,17 @@ interface HighlightProps {
1313
export const Highlight: React.FC<HighlightProps> = ({ language, text }) => {
1414
const [code, setCode] = useState<string>('');
1515

16-
const textToCode = async () => {
17-
setCode(await asyncHighlight(text as string, language));
18-
};
19-
20-
useEffect(() => {
21-
textToCode();
22-
}, []);
23-
2416
useEffect(() => {
25-
textToCode();
17+
let unmount = false;
18+
asyncHighlight(text as string, language).then((newCode) => {
19+
if (!unmount) {
20+
setCode(newCode);
21+
}
22+
});
23+
24+
return () => {
25+
unmount = true;
26+
};
2627
}, [language, text]);
2728

2829
const handleCopyClick = () => {
@@ -35,10 +36,7 @@ export const Highlight: React.FC<HighlightProps> = ({ language, text }) => {
3536
<code className={cn('hljs', language)} dangerouslySetInnerHTML={{ __html: code }} />
3637
</pre>
3738

38-
<Button
39-
onClick={handleCopyClick}
40-
className={s.copyBtn}
41-
>
39+
<Button onClick={handleCopyClick} className={s.copyBtn}>
4240
<CopyIcon />
4341
</Button>
4442
</div>

0 commit comments

Comments
 (0)