When trying to edit the data received by the Editor from outside the component, the data state updates, but the component does not re-render. Is there any way to fix this?
import { useState } from "react";
import JsonEditor from "react-json-editor-ui";
import "react-json-editor-ui/dist/react-json-editor-ui.cjs.development.css";
const App = () => {
const initialData = {
id: 1,
title: "TestProject",
arr: [],
};
let isInitial = true;
const [undoAvailable, setUndoAvailable] = useState(false);
const [redoAvailable, setRedoAvailable] = useState(false);
const [undoData, setUndoData] = useState(null);
const [redoData, setRedoData] = useState(null);
const [data, setData] = useState(initialData);
const logToConsole = () => {
console.log("data:", data);
};
const handleChange = (newData, isManual?: "undo" | "redo") => {
console.log("Changed!");
if (isManual) {
switch (isManual) {
case "undo":
setData(newData);
break;
case "redo":
setData(newData);
break;
default:
setData(newData);
}
} else {
setData(newData);
}
isInitial = false;
if (!isInitial) {
setUndoAvailable(true);
}
};
const handleUndo = () => {
console.log("Undo!");
setRedoData(data);
handleChange(undoData, "undo");
setRedoAvailable(true);
setUndoAvailable(false);
};
const handleRedo = () => {
console.log("Redo!");
setUndoData(data);
handleChange(redoData, "redo");
setRedoAvailable(false);
setUndoAvailable(true);
};
const resetData = () => {
console.log("Reset!");
setData(initialData);
isInitial = true;
};
return (
<div
style={{ border: "2px solid black", margin: "1rem", padding: "0.25rem" }}
>
<div style={{ border: "2px solid black", padding: "0.5rem" }}>
<JsonEditor
data={data}
onChange={(data) => {
handleChange(data);
}}
optionsMap={{
color: [
{ value: "red", label: "Red" },
{ value: "blue", label: "Blue" },
],
city: [
{ value: "beijing", label: "Beijing" },
{ value: "shanghai", label: "Shanghai" },
],
}}
/>
</div>
<button
onClick={() => {
logToConsole();
}}
style={{
margin: "0.5rem",
marginLeft: "0",
padding: "0.25rem",
cursor: "pointer",
}}
>
Log to console
</button>
<button
onClick={() => {
resetData();
}}
style={{
margin: "0.5rem",
marginLeft: "0",
padding: "0.25rem",
cursor: "pointer",
}}
>
Reset data
</button>
<div style={{ float: "right" }}>
<button
style={{
margin: "0.5rem",
marginRight: "0",
padding: "0.25rem",
...(undoAvailable
? { cursor: "pointer" }
: { cursor: "not-allowed" }),
}}
onClick={() => {
handleUndo();
}}
disabled={!undoAvailable}
>
Undo
</button>
<button
style={{
margin: "0.5rem",
marginRight: "0",
padding: "0.25rem",
...(redoAvailable
? { cursor: "pointer" }
: { cursor: "not-allowed" }),
}}
onClick={() => {
handleRedo();
}}
disabled={!redoAvailable}
>
Redo
</button>
</div>
</div>
);
};
export default App;