I have a scene component that I map to array of objects in editor.
And am passing the scene object as props to every scene, and i wanted to get the previous scene when i press a button.
But when I compare them in the console they are the same.
I used useRef and useEffect hooks to get prevProps
code for editor:
const scene = {
jsonObj: null,
};
const [scenes, setScenes] = useState([scene]);
useEffect(() => {
}, []);
const switchScene = (scene, prevScene) => {
const JsonObj = canvas.setJsonObj();
console.log(JsonObj);
const index = scenes.indexOf(scene);
canvas.resetEditor();
const prevIndex = scenes.indexOf(prevScene);
console.log(prevIndex, index);
let cpScenes = [...scenes];
cpScenes[prevIndex].jsonObj = JSON.stringify(JsonObj);
setScenes(cpScenes);
cpScenes = [...scenes];
cpScenes[index].jsonObj = JsonObj;
setScenes(cpScenes);
canvas.loadJson(scene.JsonObj);
console.log(scene);
console.log(prevScene);
};
return(
<div>
{scenes.map((scene, i) => (
<Scene
key={i * Math.floor(Math.random() * 100)}
addText="Scene"
onDelete={removeScene}
scene={scene}
switchScene={(scene, prevScene) => {
setUpdate(Math.floor(Math.random() * 100));
switchScene(scene, prevScene);
}}
/>
))}
);
code for scene:
import React, { useEffect, useRef, useState } from "react";
import _uniqueId from "lodash/uniqueId";
function Scene(props) {
const id = useState(_uniqueId("sceneCmpn-"));
const prevScene = useRef(props.scene);
useEffect(() => {
prevScene.current = props.scene;
}, [props.Scene]);
return (
<div key={id}>
<button
id={id}
onClick={() => {
props.switchScene(props.scene, prevScene.current);
}}
>
Scene
</button>
<button
onClick={() => props.onDelete(props.scene)}
className="btn btn-danger m-2"
>
remove scene
</button>
</div>
);
}
export default Scene;

