My array isn't getting new entries added to it via the setState
getter.
Code:
let calledOut = false;
export default function PayStation () {
const [records, setRecords] = useState([]);
// problem snippet
if (records.length === 0 && !calledOut) {
calledOut = true;
fetch('http://localhost:5000/api').then(
response => response.json()
).then(
data => {
const payloadRecords = data["records"];
// returning
// [{
// "attributes": {
// "type": "Contact",
// "url": "/services/data/v42.0/sobjects/Contact/0030U00001UPWYKQA5"
// },
// "Id": "0030U00001UPWYKQA5",
// "Name": "Contact25 Sequence Contact Manual Email"
// },
// {
// "attributes": {
// "type": "Contact",
// "url": "/services/data/v42.0/sobjects/Contact/0030U00001UPWYLQA5"
// },
// "Id": "0030U00001UPWYLQA5",
// "Name": "Contact26 Sequence Contact Manual Email"
// }
// ]
setRecords((records => [...records, ...payloadRecords]));
console.log("records size: " + records.length); // why is this still 0?
}
);
}
// end problem snippet
return (records.length === 0 ? "loading..." :
<div style={{
height: '100vh',
display: 'flex',
maxWidth: 600,
justifyContent: 'space-between',
alignItems: 'center'
}} >
{records}
</div>
);
}
I think the requirement for state to change is that you clone the state variable (which I believe I'm doing), as opposed to assigning a reference to it and mutating the reference.
So, why isn't my array getting new entries?