Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!