So I update a state using setData(arr)
. A function is called afterwards which has
return data.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage)
. The problem is that if I console.log(data)
before the return, I can see the new object added to the array but if I console.log(data.slice(...))
than the new object is not in the slice.
EDIT: I'm new to React so I'd be grateful for a very very simple explanation.
EDIT2: So I'm using a DataTable to show an array. I also have a "Add New" button which opens a sidebar and lets me add a new object to the array. Once I add it, I send it back to the parent component with a function i.e.:
const updateData = (event /* <--object from child component*/) => {
let arr = data
arr.push(event)
setData(arr)
}
I then also have a dataToRender
function which sees if the data is filtered, which for now isn't, and return the slicer array (in this case slice(20,30)).
const dataToRender = () => {
const filters = {
q: searchTerm
}
const isFiltered = Object.keys(filters).some(function (k) {
return filters[k].length > 0
})
if (dataRender.length > 0) {
return dataRender.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage)
} else if (dataRender.length === 0 && isFiltered) {
return []
} else {
return data.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage)
}
}
The problem is that if I console log data before the return, I get the new object that I added but if I use slice, than the new object isn't present.