Reputation: 4268
I am building a simple form management with a history.
I replicated a simple version of it on codesandbox
import { useState } from "react";
import "./styles.css";
const sample = ["what", "who", "where"];
const sampleL = sample.length;
export default function App() {
const [, indexSet] = useState([0, 0]);
const [, historySet] = useState([]);
const onClickNext = () => {
indexSet((index) => {
const [i] = index;
let x = i + 1;
// for loop used for some checks but in sample only runs once
for (; x < sampleL; x++) {
console.log("next > index", { index, i, x });
historySet((history) => {
const ex = [...history, i];
console.log("next > history", { h: history, i, ex });
return ex;
});
return [x, 1];
}
return index;
});
};
const onClickBack = () => {
historySet((history) => {
console.log("back > history", { h: history });
if (history.length === 0) return history;
const hx = [...history];
indexSet([hx.pop(), -1]);
return hx;
});
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<p>Open console, click next twice, click back once</p>
<p>Why is history with three values instead of two?</p>
<button onClick={onClickNext}>Next</button>
<button onClick={onClickBack}>Back</button>
</div>
);
}
I kept the code as close to my original source. However, on my computer, the multiple runs of indexSet is recorded via console. On codesandbox, the array magically has an additional item. Both result with the same error.
Why is indexSet running twice, causing history to become [0,1,1]? Is this an error with React?
Upvotes: 1
Views: 280
Reputation: 4268
As per React, its expected behavior. https://github.com/facebook/react/issues/24057
Upvotes: 2