Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda