Is there a way to save the state of my game even after a page refresh using local or session storage? I've successfully stored wins in localStorage, but I'm struggling to keep the table with "X" and "O" in the same spot after a refresh. Any suggestions?
import { ref, computed, watch, onMounted } from "vue";
const player = ref("X");
const table = ref([
["", "", ""],
["", "", ""],
["", "", ""],
]);
const CalculateWinner = (squares) => {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
};
const winner = computed(() => CalculateWinner(table.value.flat()));
const Move = (x, y) => {
if (winner.value) return;
if (table.value[x][y] !== "") return;
table.value[x][y] = player.value;
player.value = player.value === "X" ? "O" : "X";
};
const Reset = () => {
table.value = [
["", "", ""],
["", "", ""],
["", "", ""],
];
player.value = "X";
};
const history = ref([]);
watch(winner, (current, previous) => {
if (current && !previous) {
history.value.push(current);
localStorage.setItem("history", JSON.stringify(history.value));
}
});
onMounted(() => {
history.value = JSON.parse(localStorage.getItem("history")) ?? [];
});