This is my reducer for a snake game I'm making. Basically, whenever I want to reset the game, I update the state to INITIAL_STATE
as seen in NEW_GAME
, but whenever MOVE_SNAKE
fires, it seems to be modifying INITIAL_STATE
, so I'm basically passing it the current state and NEW_GAME
does nothing.
I added that console.log(INITIAL_STATE.coords[0])
to confirm, and any time the snake moves, the INITIAL_STATE
updates to the current state too. Why is this? I've done something similar like this in a tic tac toe game, but now it's not working?
// REDUCER
const INITIAL_STATE = {
coords: [
[1, 0],
[1, 1],
[1, 2]
]
};
export default function(state = INITIAL_STATE, action) {
console.log(INITIAL_STATE.coords[0]);
switch(action.type) {
case 'MOVE_SNAKE':
return {
...state,
coords: action.coords
}
case 'NEW_GAME':
return INITIAL_STATE;
}
return state;
}
// ACTION CREATORS
export function moveSnake(snake) {
let { coords, direction } = snake;
let headCoords = coords[coords.length-1];
let newHead = () => {
if(direction === 'DOWN') return [headCoords[0], headCoords[1]+1];
if(direction === 'UP') return [headCoords[0], headCoords[1]-1];
if(direction === 'LEFT') return [headCoords[0]-1, headCoords[1]];
if(direction === 'RIGHT') return [headCoords[0]+1, headCoords[1]];
};
coords.push(newHead());
coords.shift();
return {
type: 'MOVE_SNAKE',
coords
}
}
// COMPONENT CALL LOOKS LIKE THIS
this.props.moveSnake(this.props.snake);
I've tried using Object.assign()
on everything, and it still was messing with my INITIAL_STATE
.