I am not getting the updated state values inside FabricJS events like object:modified, mouse:up, etc... But I can able to set state value inside that callback functions.
When I tried to get the state value, it is returning the initial values and not the updated one.
Example:
const [count, setCount] = useState(0);
The initial value is 0. I update the value using setCount to 1. Whenever I tried to get the "count" inside the callback function, it is returning 0 or the initial value.
Edit:
What I am trying to achieve is that I am trying to save FabricJS object whenever object modified (For Undo, Redo operations). Whenever an object changes, FabricJS is triggering an event and calls a function in the component. But I don't get the state value.
Code:
function MyFunction()
{
const [canvasObj, setCanvasObj] = useState({});
const [state, setCanvasState] = useState('');
const [undo, setUndo] = useState([]);
useEffect(() => {
if(Object.keys(canvasObj).length == 0) {
var _canvas = new fabric.Canvas('canvas', {
preserveObjectStacking: true,
});
setCanvasObj(_canvas);
_canvas.on("object:modified", saveState);
}
});
function saveState() {
console.log(canvasObj); // Returns null even though object initialised
if (state) { // state value returns null. Due to this, I can't get the existing data and push the current state
let newState = undo;
newState.push(state);
setUndo(newState);
}
const tmpState = JSON.stringify(canvasObj);
setCanvasState(tmpState);
}
}