I tried to update the state using useEffect hook and it causing some errors.The state is updated to sessionStorage whenever any changes made. I tried to use setElements in useEffect , I think this might be causing the problem. Is there a best way to set and get sessionStorage item along with updating the array state.(without using redux).
//This is the initial Element Node which will appear by default at start
let prevElement = [{
id: "0",
type: "input",
data: { label: "Input Node", specificElType: "start" },}]
const DnDFlow = () => {
const [elements, setElements] = useState(prevElement);
...
...
...
//I tried to restore the previous work if stored in sessionStorage
useEffect(() => {
if(JSON.parse(sessionStorage.getItem("flowchart-elements")) != null && JSON.parse(sessionStorage.getItem("flowchart-elements")) != undefined){
setElements(JSON.parse(sessionStorage.getItem("flowchart-elements")));
}});
...
...
...
const onNodeDrag = async (event, node) => {
sessionStorage.setItem("flowchart-elements",JSON.stringify(elements));
}
Thank you
For a
useEffect()
to run just on refresh, it needs to include an empty dependency array as its second parameter as shown below: