Fixed draw function by wrapping it with usecallback

This commit is contained in:
Dmitriy Shishkov 2021-09-04 04:18:39 +03:00
parent 77661df39b
commit 7b34e5a5e5
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060

View File

@ -1,22 +1,42 @@
import { useCallback, useEffect, useState } from "react";
import { useRoomContext } from "../context";
import { Canvas } from "./Canvas";
export type BuildingPlanProps = { width: number; height: number };
export const BuildingPlan = ({ width, height }: BuildingPlanProps) => {
const { state } = useRoomContext();
const { state, setState } = useRoomContext();
const draw = useCallback(
(ctx: CanvasRenderingContext2D) => {
state.map.map(({ coordinates, size }, index) => {
const { free } = state.char[index];
ctx.fillStyle = free ? "green" : "gray";
ctx.fillRect(coordinates.x, coordinates.y, size.w, size.h);
});
},
[state.char, state.map]
);
useEffect(() => {
setTimeout(
() =>
setState((p) => ({
...p,
char: [
{ free: false },
{ free: false },
{ free: false },
{ free: false },
],
})),
1000
);
}, []);
return (
<Canvas
height={height}
width={width}
draw={(ctx) => {
state.map.map(({ coordinates, size }, index) => {
const { free } = state.char[index];
ctx.fillStyle = free ? "green" : "gray";
ctx.fillRect(coordinates.x, coordinates.y, size.w, size.h);
});
}}
/>
<>
<Canvas height={height} width={width} draw={draw} />
</>
);
};