I was practising on the new react docs.
here: https://beta.reactjs.org/learn/updating-objects-in-state#challenges
Challenge 2 of 3: Find and fix the mutation
I solved it but when trying to log the initialPosition object to see its value, the background didn't follow the box. that means that somehow adding the console log solved the state mutation.
I am wondering how that happened and whether it is a bug or not.
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) {
shape.position.x += dx;
shape.position.y += dy;
console.log({initialPosition}); //<====== HERE =====================================
}
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>
</>
);
}