Updating Objects in State·续2
const initialPosition = { x: 0, y: 0 };
export default function Canvas() { const [shape, setShape] = useState({ color: 'orange', position: initialPosition });
function handleMove(dx, dy) { shape.position.x += dx; shape.position.y += dy; }
function handleColorChange(e) { setShape({ ...shape, color: e.target.value }); }
return ( <> <select value={shape.color} onChange={handleColorChange} > <option value="orange">orange</option> <option value="lightpink">lightpink</option> <option value="aliceblue">aliceblue</option> </select> <Background position={initialPosition} /> <Box color={shape.color} position={shape.position} onMove={handleMove} > Drag me! </Box> </> ); }
```js src/Box.js
import { useState } from 'react';
export default function Box({
children,
color,
position,
onMove
}) {
const [
lastCoordinates,
setLastCoordinates
] = useState(null);
function handlePointerDown(e) {
e.target.setPointerCapture(e.pointerId);
setLastCoordinates({
x: e.clientX,
y: e.clientY,
});
}
function handlePointerMove(e) {
if (lastCoordinates) {
setLastCoordinates({
x: e.clientX,
y: e.clientY,
});
const dx = e.clientX - lastCoordinates.x;
const dy = e.clientY - lastCoordinates.y;
onMove(dx, dy);
}
}
function handlePointerUp(e) {
setLastCoordinates(null);
}
return (
<div
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
style={{
width: 100,
height: 100,
cursor: 'grab',
backgroundColor: color,
position: 'absolute',
border: '1px solid black',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
transform: `translate(
${position.x}px,
${position.y}px
)`,
}}
>{children}</div>
);
}
``js src/Background.js
export default function Background({
position
}) {
return (
<div style={{
position: 'absolute',
transform:translate(
${position.x}px,
${position.y}px
)`,
width: 250,
height: 250,
backgroundColor: 'rgba(200, 200, 0, 0.2)',
}} />
);
};
```css
body { height: 280px; }
select { margin-bottom: 10px; }
The problem was in the mutation inside handleMove. It mutated shape.position, but that's the same object that initialPosition points at. This is why both the shape and the background move. (It's a mutation, so the change doesn't reflect on the screen until an unrelated update--the color change--triggers a re-render.)
The fix is to remove the mutation from handleMove, and use the spread syntax to copy the shape. Note that += is a mutation, so you need to rewrite it to use a regular + operation.
```js src/App.js import { useState } from 'react'; import Background from './Background.js'; import Box from './Box.js';
const initialPosition = { x: 0, y: 0 };
export default function Canvas() { const [shape, setShape] = useState({ color: 'orange', position: initialPosition });
function handleMove(dx, dy) { setShape({ ...shape, position: { x: shape.position.x + dx, y: shape.position.y + dy, } }); }
function handleColorChange(e) { setShape({ ...shape, color: e.target.value }); }
return ( <> <select value={shape.color} onChange={handleColorChange} > <option value="orange">orange</option> <option value="lightpink">lightpink</option> <option value="aliceblue">aliceblue</option> </select> <Background position={initialPosition} /> <Box color={shape.color} position={shape.position} onMove={handleMove} > Drag me! </Box> </> ); }
```js src/Box.js
import { useState } from 'react';
export default function Box({
children,
color,
position,
onMove
}) {
const [
lastCoordinates,
setLastCoordinates
] = useState(null);
function handlePointerDown(e) {
e.target.setPointerCapture(e.pointerId);
setLastCoordinates({
x: e.clientX,
y: e.clientY,
});
}
function handlePointerMove(e) {
if (lastCoordinates) {
setLastCoordinates({
x: e.clientX,
y: e.clientY,
});
const dx = e.clientX - lastCoordinates.x;
const dy = e.clientY - lastCoordinates.y;
onMove(dx, dy);
}
}
function handlePointerUp(e) {
setLastCoordinates(null);
}
return (
<div
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
style={{
width: 100,
height: 100,
cursor: 'grab',
backgroundColor: color,
position: 'absolute',
border: '1px solid black',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
transform: `translate(
${position.x}px,
${position.y}px
)`,
}}
>{children}</div>
);
}
``js src/Background.js
export default function Background({
position
}) {
return (
<div style={{
position: 'absolute',
transform:translate(
${position.x}px,
${position.y}px
)`,
width: 250,
height: 250,
backgroundColor: 'rgba(200, 200, 0, 0.2)',
}} />
);
};
```css
body { height: 280px; }
select { margin-bottom: 10px; }
Update an object with Immer
This is the same buggy example as in the previous challenge. This time, fix the mutation by using Immer. For your convenience, useImmer is already imported, so you need to change the shape state variable to use it.
```js {expectedErrors: {'react-compiler': [18]}} src/App.js import { useState } from 'react'; import { useImmer } from 'use-immer'; import Background from './Background.js'; import Box from './Box.js';
const initialPosition = { x: 0, y: 0 };
export default function Canvas() { const [shape, setShape] = useState({ color: 'orange', position: initialPosition });
function handleMove(dx, dy) { shape.position.x += dx; shape.position.y += dy; }
function handleColorChange(e) { setShape({ ...shape, color: e.target.value }); }
return ( <> <select value={shape.color} onChange={handleColorChange} > <option value="orange">orange</option> <option value="lightpink">lightpink</option> <option value="aliceblue">aliceblue</option> </select> <Background position={initialPosition} /> <Box color={shape.color} position={shape.position} onMove={handleMove} > Drag me! </Box> </> ); }
```js src/Box.js
import { useState } from 'react';
export default function Box({
children,
color,
position,
onMove
}) {
const [
lastCoordinates,
setLastCoordinates
] = useState(null);
function handlePointerDown(e) {
e.target.setPointerCapture(e.pointerId);
setLastCoordinates({
x: e.clientX,
y: e.clientY,
});
}
function handlePointerMove(e) {
if (lastCoordinates) {
setLastCoordinates({
x: e.clientX,
y: e.clientY,
});
const dx = e.clientX - lastCoordinates.x;
const dy = e.clientY - lastCoordinates.y;
onMove(dx, dy);
}
}
function handlePointerUp(e) {
setLastCoordinates(null);
}
return (
<div
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
style={{
width: 100,
height: 100,
cursor: 'grab',
backgroundColor: color,
position: 'absolute',
border: '1px solid black',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
transform: `translate(
${position.x}px,
${position.y}px
)`,
}}
>{children}</div>
);
}
``js src/Background.js
export default function Background({
position
}) {
return (
<div style={{
position: 'absolute',
transform:translate(
${position.x}px,
${position.y}px
)`,
width: 250,
height: 250,
backgroundColor: 'rgba(200, 200, 0, 0.2)',
}} />
);
};
```css
body { height: 280px; }
select { margin-bottom: 10px; }
```json package.json { "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
This is the solution rewritten with Immer. Notice how the event handlers are written in a mutating fashion, but the bug does not occur. This is because under the hood, Immer never mutates the existing objects.
```js src/App.js
import { useImmer } from 'use-immer';
import Background from './Background.js';
import Box from './Box.js';
const initialPosition = {
x: 0,
y: 0
};
export default function Canvas() {
const [shape, updateShape] = useImmer({
color: 'orange',
position: initialPosition
});
function handleMove(dx, dy) {
updateShape(draft => {
draft.position.x += dx;
draft.position.y += dy;
});
}
function handleColorChange(e) {
updateShape(draft => {
draft.color = e.target.value;
});
}
return (
<>
<select
value={shape.color}
onChange={handleColorChange}
>
<option value="orange">orange</option>
<option value="lightpink">lightpink</option>
<option value="aliceblue">aliceblue</option>
</select>
<Background
position={initialPosition}
/>
<Box
color={shape.color}
position={shape.position}
onMove={handleMove}
>
Drag me!
</Box>
</>
);
}
```js src/Box.js import { useState } from 'react';
export default function Box({ children, color, position, onMove }) { const [ lastCoordinates, setLastCoordinates ] = useState(null);
function handlePointerDown(e) { e.target.setPointerCapture(e.pointerId); setLastCoordinates({ x: e.clientX, y: e.clientY, }); }
function handlePointerMove(e) { if (lastCoordinates) { setLastCoordinates({ x: e.clientX, y: e.clientY, }); const dx = e.clientX - lastCoordinates.x; const dy = e.clientY - lastCoordinates.y; onMove(dx, dy); } }
function handlePointerUp(e) { setLastCoordinates(null); }
return (
<div
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
style={{
width: 100,
height: 100,
cursor: 'grab',
backgroundColor: color,
position: 'absolute',
border: '1px solid black',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
transform: translate(
${position.x}px,
${position.y}px
),
}}
>{children}</div>
);
}
```js src/Background.js
export default function Background({
position
}) {
return (
<div style={{
position: 'absolute',
transform: `translate(
${position.x}px,
${position.y}px
)`,
width: 250,
height: 250,
backgroundColor: 'rgba(200, 200, 0, 0.2)',
}} />
);
};
body { height: 280px; }
select { margin-bottom: 10px; }
json package.json
{
"dependencies": {
"immer": "1.7.3",
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"use-immer": "0.5.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
