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