Retrieve the parent's current state by accessing it through a callback function in React

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:

https://i.sstatic.net/xg0St.png

Answer №1

It is recommended to store the data for each snapshot in state and use it to generate the JSX, rather than storing the JSX itself in state.

const [history, setHistory] = useState([{board: EMPTY_BOARD, currentPlayer: true}]);
// ...
return (
    <div className="Game">
        <h1>History: 
            { history.map((s, i) => <Snapshot key={i} {...s} index={i} onRestore={onRestore} />) }
        </h1>
    </div>
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my jQuery to only toggle the first arrow in my HTML?

I am facing an issue with a series of divs generated from data, each containing an arrow that should toggle an expandable section. Strangely, only the first div is functioning properly: toggling the arrow icon and revealing the content upon click. When th ...

Can data stored in one App be accessed by another App through the use of reactjs?

I have two applications that I am trying to connect, but the only key I have is the user ID. Therefore, I want to store the user ID in local storage and retrieve it in the other application. In ReactJS, I am storing data in local storage. App1: localStor ...

Is there a way to customize the directory that React searches for the production build?

After creating my frontend build using the command npm build, I moved it to the backend folder with a path of "backend/build". When I tried running npm start in the backend directory, I encountered an issue where nothing displayed when I visited localhost: ...

Token Fields malfunctioning

I attempted to use a sample from bootstrap, but I am not having any luck with it. Is there anyone who can assist me in resolving this issue and understanding it better? Code Snippet: <input type="text" class="form-control" id="tokenfield" value="red, ...

What is the best way to send the current state in React using axios?

I'm currently attempting to make a post request using axios within Reactjs. Within my project, I have two components - a timer component and an App component. In the App component, I am working on submitting a form and making an axios call when I fet ...

The console is throwing an error: ReferenceError: The variable $ has not been defined

I am having issues when trying to dynamically add a div upon selecting a checkbox in a Django template. The error message Uncaught ReferenceError: $ is not defined keeps appearing in the console. Here is the template code: {% extends 'base_layout.htm ...

Updating Text in Textarea upon Selection Change

Need assistance with updating the content of a textarea based on a select option change. Below is an example of my code: <tr><td>Template:</td><td> <select t name="template" onChange = "setTemplate();"> <option ...

Personalizing Material-UI's select component: A step-by-step guide

Desired Outcome: https://i.stack.imgur.com/khNHn.png https://i.stack.imgur.com/dQzVz.png Progress So Far: https://i.stack.imgur.com/CUixn.png Struggling to Position SVG Icon Next to Text: https://i.stack.imgur.com/4GFtA.png Issue with Black Line Whe ...

Enhance Select Dropdown in AngularJS with Grouping and Default Selection

I am facing an issue with a form that includes a SELECT element. I have successfully loaded the possible values in my controller from a function that retrieves data from a database and groups the options by a group name. Although the list of options is lo ...

Unable to render dynamic ID in Next.js version 13.4.6 due to an issue

Currently diving into next-js! Previously, I utilized dynamic id rendering in my projects. However, encountering errors now with the current version (next js 13.4.6). Having trouble identifying the issue. Could it be due to not having a 'pages' f ...

Jest testing in a Vue child component is failing due to the presence of lodash

In this specific instance of my Vue app, I have globally loaded lodash as a Vue plugin in the main.js file: import _ from "lodash" export default function install(Vue) { Vue.prototype._ = _ Vue.mixin({ computed: { _: () => ...

When an input element is being controlled from outside the modal using a portal, it is losing focus after a key press

[Resolved] The input component is experiencing a focus issue when any key is pressed, only when its value is controlled from outside of the portal. NOTE: I apologize for any confusion. While writing this post, I identified the problem in my code, but dec ...

What are some ways to streamline and improve the readability of my if/else if statement?

I've created a Rock Paper Scissors game that runs in the console. It currently uses multiple if/else if statements to compare user input against the computer's selection and determine a winner. The code is quite lengthy and repetitive, so I' ...

A guide to filtering a JSON array by email address with JavaScript

How can I identify distinct elements in a JSON array using JavaScript? Below is the example of my JSON array. I need to determine the size of unique elements. [ { "_id": "5aaa4f8cd0ccf521304dc6bd", "email": "<a h ...

What is causing the z-index to not function properly on my elements?

In my current code setup, I have positioned the hero image at the bottom with an overlay on top that contains text and a button. Additionally, there is a navigation bar with a z-index applied. However, I am facing an issue where the button for viewing my r ...

Adjust the text size for groupBy and option labels in Material UI Autocomplete without altering the size of the input field

Currently, I am utilizing Material-UI and ReactJS to implement grouped autocomplete functionality. See the code snippet below: import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from &q ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Is there a way to properly direct to an internal page while utilizing [routerLink] and setting target="_blank" without triggering a full page reload?

I'm attempting to use [routerLink] along with target="_blank" to direct to an internal page without triggering a full app reload. Currently, the page opens in a new tab, but the whole application is refreshed. Here is the HTML: <a [routerLink]=" ...

I'm encountering an unfamiliar error within my Discord.js bot, and I'm unsure of both its cause and the appropriate solution. Additionally, I'm unsure which specific file

I'm facing a recurring issue with my bot terminal. It's been causing me trouble for the past four days, functioning intermittently without any pattern. I'm struggling to track down the specific file where this error is originating from. Any ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...