Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix bugs when refresh with modal active #79

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions projects/02-tic-tac-toe/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ function App () {
})

// null es que no hay ganador, false es que hay un empate
const [winner, setWinner] = useState(null)
const [winner, setWinner] = useState(() => {
const winnerFromStorage = window.localStorage.getItem('winner')
if (winnerFromStorage === 'null') return null
return winnerFromStorage
})

const resetGame = () => {
setBoard(Array(9).fill(null))
Expand All @@ -41,19 +45,22 @@ function App () {
// cambiar el turno
const newTurn = turn === TURNS.X ? TURNS.O : TURNS.X
setTurn(newTurn)
// guardar aqui partida
saveGameToStorage({
board: newBoard,
turn: newTurn
})

// revisar si hay ganador
const newWinner = checkWinnerFrom(newBoard)
let newWinner = checkWinnerFrom(newBoard)
if (newWinner) {
confetti()
setWinner(newWinner)
} else if (checkEndGame(newBoard)) {
setWinner(false) // empate
newWinner = false
}
// guardar aqui partida
saveGameToStorage({
board: newBoard,
turn: newTurn,
winner: newWinner
})
}

return (
Expand Down
4 changes: 3 additions & 1 deletion projects/02-tic-tac-toe/src/logic/storage/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
export const saveGameToStorage = ({ board, turn }) => {
export const saveGameToStorage = ({ board, turn, winner }) => {
// guardar aqui partida
window.localStorage.setItem('board', JSON.stringify(board))
window.localStorage.setItem('turn', turn)
window.localStorage.setItem('winner', winner)
}

export const resetGameStorage = () => {
window.localStorage.removeItem('board')
window.localStorage.removeItem('turn')
window.localStorage.removeItem('winner')
}