Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
React setState resets string

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 "" i feel sad :(

Thanks.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I found the problem useState setter method not updating immediately. Thanks everyone.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda