0

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.

DjangoDev1
  • 232
  • 4
  • 14
  • Can you show a more complete example? Ideally a [Minimal Reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). It would be easier to understand the cause and explain it that way – Brian Thompson Feb 28 '21 at 00:48
  • Sorry, I've just added an explanation as well as the minimum code needed. I also forgot to mention that I even tried to have something like this before the `return...`: `let data = arr; return arr.slice(...)` but even this doesn't work which I'm not sure why. – DjangoDev1 Feb 28 '21 at 00:53

0 Answers0