Ref
I am getting an interesting error when using a ref to select a canvas. Code works but just wondering if I am using ref the right way.
The error is
am I doing something wrong?
The error is
Variable 'canvasRef' is used before being assigned.ts(2454)Variable 'canvasRef' is used before being assigned.ts(2454) am I doing something wrong?
import { Show, createEffect } from "solid-js";
import { createStore } from "solid-js/store";
export default function Form() {
const [store, setStore] = createStore({
image: null,
imagePreviewURL: "",
});
let canvasRef : HTMLCanvasElement;
createEffect(() => {
console.log("imagePreviewURL changed");
if (store.imagePreviewURL) {
const ctx = canvasRef.getContext("2d");
const img = new Image();
img.onload = function() {
canvasRef.width = img.width;
canvasRef.height = img.height;
ctx!.drawImage(img, 0, 0);
}
img.src = store.imagePreviewURL;
}
})
const uploadFile = async (e: any) => {
const image = e.target.files[0];
const imagePreview = URL.createObjectURL(image);
setStore("image", image);
setStore("imagePreviewURL", imagePreview);
}
return (
<div>
<form>
<label>Select a single file </label>
<input type="file" onChange={uploadFile} accept="image/*" />
</form>
<Show when={store.imagePreviewURL}>
<canvas id="canvas" ref={canvasRef} style={{"max-width": "400px"}}></canvas>
</Show>
</div>
)
}import { Show, createEffect } from "solid-js";
import { createStore } from "solid-js/store";
export default function Form() {
const [store, setStore] = createStore({
image: null,
imagePreviewURL: "",
});
let canvasRef : HTMLCanvasElement;
createEffect(() => {
console.log("imagePreviewURL changed");
if (store.imagePreviewURL) {
const ctx = canvasRef.getContext("2d");
const img = new Image();
img.onload = function() {
canvasRef.width = img.width;
canvasRef.height = img.height;
ctx!.drawImage(img, 0, 0);
}
img.src = store.imagePreviewURL;
}
})
const uploadFile = async (e: any) => {
const image = e.target.files[0];
const imagePreview = URL.createObjectURL(image);
setStore("image", image);
setStore("imagePreviewURL", imagePreview);
}
return (
<div>
<form>
<label>Select a single file </label>
<input type="file" onChange={uploadFile} accept="image/*" />
</form>
<Show when={store.imagePreviewURL}>
<canvas id="canvas" ref={canvasRef} style={{"max-width": "400px"}}></canvas>
</Show>
</div>
)
}
