Reputation: 64
I'm trying to get writed line from XTerm.js with a callback from parent element whenever user puts a new char to the terminal then parent element updates the string which is adds char from child to last of the string. But whenever i call the addChar() function line state resets to "".
App.tsx:
import React, { useEffect, useState } from "react";
import "./App.css";
import XTerm from "./components/XTerm";
function App() {
const [currentLine, setCurrentLine] = useState<string>("");
useEffect(() => {
console.log(currentLine);
}, [currentLine]);
const addChar = (char: string) => {
let newLine = currentLine + char;
console.log(currentLine, char);
setCurrentLine(newLine);
};
return (
<div className="App">
<div className="Inner">
<XTerm
addChar={addChar}
/>
</div>
</div>
);
}
export default App;
XTerm.tsx:
import { FunctionComponent, useEffect, useRef } from "react";
import "xterm/css/xterm.css";
import { Terminal } from "xterm";
type types = {
addChar: (char: string) => void;
};
const XTerm: FunctionComponent<types> = ({
addChar,
}) => {
const terminalElement = useRef<HTMLDivElement>(null);
useEffect(() => {
var term = new Terminal();
term.open(terminalElement.current as HTMLDivElement);
term.onKey(({ domEvent }) => {
addChar(domEvent.key);
return term.write(key);
});
term.write("Hostname: ");
return () => {
term.clear();
};
}, []);
return <div ref={terminalElement}></div>;
};
export default XTerm;
The problem is string resets to ""
Thanks.
Upvotes: 1
Views: 283
Reputation: 64
I finally find the actual problem. States are not changing in event handlers. So the onKey callback event only takes the first initialized value of the state.
Upvotes: 1
Reputation: 64
I found the problem useState setter method not updating immediately. Thanks everyone.
Upvotes: 0