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

182
Vistas
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 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