My callback function onRestore
is only logging the history until the id of the clicked snapshot. Why is it showing incorrect state? I've exhausted all options, so any help would be appreciated.
import React, { useState, useEffect, useRef } from "react"
import Board from "./Board"
import Snapshot from "./Snapshot"
export default function Game(){
const [ history, setHistory ] = useState([makeSnapshot(0, EMPTY_BOARD, true, onRestore)])
const [ offset, setOffset ] = useState(0)
function makeSnapshot(index, board, currentPlayer, onRestore){
const snapshot = { index, board, currentPlayer, onRestore }
return <Snapshot key={index} {...snapshot}/>
}
function onRestore(snapshot){
console.log(snapshot) // #2 snapshot item
console.log(history) // log only 2 snapshot items (if snapshot item id is #3 so 3 items in history)
}
function drawPlayer(index){
const nextMove = makeSnapshot(history.length, newBoard, currentPlayer, onRestore)
setHistory(prevHistory => ([...prevHistory, nextMove]))
setOffset(history.length + 1)
}
return(
<div className="Game">
<h1>History: { history.map(snapshot => snapshot) } </h1>
</div>
)
}
export default function Snapshot(snapshot){
const move = !snapshot.index ? `game start` : `move #${snapshot.index}`
const disableClass = snapshot.isDisabled ? " disabled" : ""
return(
<div id={snapshot.index} className="snapshot" onClick={() => snapshot.onRestore(snapshot)}> Go to {move} </div>
)
}
https://i.sstatic.net/ewaij.png
Live log: