How to store data in state in canvas? #124
-
I am using your npm package [react-sketch-canvas] for the doctor to write prescription in scratch pad. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I know this is old but I thought it might still be helpful for someone going through a similar situation. To store the canvas paths you can access const canvasRef = useRef<ReactSketchCanvasRef>(null);
<ReactSketchCanvas
ref={canvasRef}
onChange={handleCanvasOnChange}
style={styles}
width="600"
height="800"
strokeWidth={4}
strokeColor="black"
/> Then, you can create a Save button or use the const [canvas, setCanvas] = useState<CanvasPath[]>([]);
const handleCanvasOnChange = (e: any) => {
const exportedCanvasPromise = canvasRef?.current?.exportPaths();
exportedCanvasPromise?.then((result: any[]) => {
localStorage.setItem('paths', JSON.stringify(result))
setCanvas(result)
}).catch((error: any) => {
console.error(error);
});
}
Then you can retrieve that data and load to your canvas using useEffect(() => {
if (canvasRef) {
let paths = localStorage.getItem('paths')
if (paths) {
let jsonPaths = JSON.parse(paths)
canvasRef?.current?.loadPaths(jsonPaths)
}
}
}, []) |
Beta Was this translation helpful? Give feedback.
I know this is old but I thought it might still be helpful for someone going through a similar situation.
To store the canvas paths you can access
exportPaths
method usingref
like this:Then, you can create a Save button or use the
onChange
prop to save it every time the user interacts with the canvas (if you choose the second method I think you could add some debounce logic to avoid saving too frequently)