I am trying to initialize the state during the mounting cycle, and then do something with it on each update.
However, the state gets reset somehow? I don't understand why.
const [journalItems, setJournalItems] = useState([]);
useEffect(() => {
fetch(`http://localhost:4000/journals/${props.match.params.key}/items`)
.then(res => res.json())
.then(data => {
setJournalItems(data) // Sets the state when the AJAX completes
})
.catch(err => err);
table.current = new Tabulator(refTable.current, {
rowClick: function (e, row) {
console.log("tabulator journalitems", journalItems) // State is lost returns []
handleTableRowClick(row._row.data.id)
},
columns: [
{ title: "Компанија", field: "companyName" },
{ title: "Документ", field: "documentKey" },
],
});
}, []);
useEffect(() => {
console.log("useEffect journalItems", journalItems) // Works fine
table.current.replaceData(journalItems) // Uses the new state
}, [journalItems]);
function handleTableRowClick(journalItemId) {
console.log("handletablerowclick journalitems", journalItems) // State is lost, resets to []
}
Results form the console logs...
useEffect journalItems []
useEffect journalItems (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
tabulator journalitems []
handleTableRowClick journalitems []