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

184
Visualizações
Lose state in onChange function in React JS

I have this code:

import "./styles.css";
import React, { useEffect, useRef, useState } from "react";
import JSONEditor from "jsoneditor";
import "jsoneditor/dist/jsoneditor.css";

const JSONReact = ({ json, setValid, onChange }) => {
  const ref1 = useRef(null);
  const ref2 = useRef(null);

  useEffect(() => {
    const props = {
      onChangeText: (value) => {
        // console.log(value, 'vv')
        onChange(value);
      },
      onValidationError: (e) => {
        setValid(Boolean(!e.length));
      },
      modes: ["code"]
    };
    ref1.current = new JSONEditor(ref2.current, props);

    if (json) {
      ref1.current.set(json);
    }

    return () => {
      ref1.current.destroy();
    };
  }, []);

  return <div ref={ref2} />;
};

export default function App() {
  const [state, setState] = useState('{"cars": "22w-08w-23"}');
  const [valid, setValid] = useState(true);
  const onChange = (j) => {
    console.log(valid);
    // setState(j);
  };
  return (
    <div className="App">
      <JSONReact
        mode="code"
        onChange={onChange}
        json={JSON.parse(state)}
        setValid={setValid}
      />
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I need the updated value regarding error here console.log(valid);, but it does not update inside onChange function.
Question: What is the issue and how to solve it?
demo: https://codesandbox.io/s/admiring-khorana-pdem1l?file=/src/App.js:0-1233

about 4 years ago · Juan Pablo Isaza
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