I'm using useRef()
to call a childs function from my parent component. The issue is the childs state (betHistory
) is empty whenever the parent calls the childs undo
function, but when undo()
is called by the child itself, the state is in date (filled with all the values that have been pushed to it). Why is my parent seeing an empty version of betHistory
when calling undo()
vs when undo()
is called by the child itself?
Parent
import './App.css';
import Table from './Table';
import React, { useEffect, useState, useRef } from 'react';
function App() {
const table = useRef();
function undo() {
table.current.undo();
}
return (
<div className="App">
<div className="table-section">
<Table ref={table}></Table>
</div>
<div className="button" onClick={undo}>Click me</div>
</div>
);
}
export default App;
Child
import React, { useState, forwardRef, useImperativeHandle } from 'react';
import './Table.css';
function Table(props, ref) {
const [betHistory, setBetHistory] = useState([]);
const [betCount, setBetCount] = useState(0);
function placeBet(element) {
const newBetHistory = [...betHistory, betCount.toString()];
setBetHistory(newBetHistory);
setBetCount((1 betCount));
}
function undo() {
console.log(betHistory);
}
useImperativeHandle(ref, () => ({
undo() {
undo();
}
}), [])
return (
<div className="button" onClick={undo}>Click me</div>
<div className="bet-button" onClick={placeBet}></div>
);
}
export default forwardRef(Table)
CodePudding user response:
useImperativeHandle(ref, () => ({
undo() {
undo();
}
}), []) // ---> Try remove this []
It has to do with the empty array you specified. Try removing it. Just like in useEffect
when you specify empty array as dependency it will run only once, so the function captured inside is from first render, hence you don't see recent data.
Or you can specify correct dependencies.