I'm using Preact (for all intents and purposes, React) to render a list of items, saved in a state array. Each item has a remove button next to it. My problem is: when the button is clicked, the proper item is removed (I verified this several time), but the items are re-rendered with the last item missing, and the removed one still there. My code (simplified):
import {Component} from "preact";
import Package from "./package";
export default class Packages extends Component {
constructor(props) {
super(props);
this.state = {packages: ["a", "b", "c", "d", "e"]};
}
removePackage(tracking) {
this.setState(state => (
{packages: state.packages.filter(item => item !== tracking)}
));
}
render() {
const packages = this.state.packages.map((tracking, index) => (
<div className="package" key={index}>
<button onClick={() => this.removePackage(tracking)}>
X
</button>
<Package tracking={tracking} />
</div>
));
return(
<div>
<div className="title">Packages</div>
<div className="packages">{packages}</div>
</div>
);
}
}
What am I doing wrong? Do I need to actively re-render somehow? Is this an n+1 case somehow?
Clarification: My problem is not with the synchronicity of state. In the list above, if I elect to remove "c"
, the state is updated correctly to ["a", "b", "d", "e"]
, but the components rendered are ["a", "b", "c", "d"]
. At every call to removePackage
the correct one is removed from the array, the proper state is shown, but a wrong list is rendered. (I removed the console.log
statements, so it won't seem like they are my problem).
setState
and event handlers, and never even looked at thekey
:) – Fatigue