0

I have a problem with the slice() function.

My code:

constructor(props){
  super(props);
  this.state({
    data: props.data
  })
}

//my function
onSliceData = () => {
  let data = this.state.data;
  let sliceData = data.slice(0,5);
  return sliceData;
}

My problem is my function does not return anything. When I console.log(data) in onSliceData I receive result like this:

And when I console.log(sliceData) I just receive [] I try using Object.keys to convert data to array but maybe not working. I need some help.

4
  • Object.keys doesn't convert an object to an array. Commented Dec 13, 2019 at 17:35
  • yes. Object.keys just returns array is the key of object. I wanna return array of object , example: [{}, {},...] what should I do? Commented Dec 13, 2019 at 17:44
  • Check my answer and onSliceData should return an array of objects if props.data is an array of objects :) Commented Dec 13, 2019 at 17:47
  • I think there's a problem with storing data, not the slice itself. Commented Nov 24, 2021 at 8:13

3 Answers 3

2

Try to use Array.from(data).slice.
It worked for me same on ReactJS.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this (I found this with the help of w3schools):

let sliceData = data.toString().slice(0,5);

I tried this method and it worked just fine!

Comments

0

Make sure that the props being received have data(which is an array)

In the constructor:

constructor(props){
  super(props);
  this.state = { // assign the state with an js object instead of calling it as a func.
    data: props.data
  }
}

Try this:

onSliceData = () => {
  let data = [...this.state.data]; // spreading will return a new array
  let sliceData = data.slice(0,5);
  return sliceData;
}

10 Comments

thank you, but not working to me :( it returns [] nothing inside :(
when and where are you calling onSliceData?
I call at componentDidMount(){ this.onSliceData()}
and where are you logging the returned value?
I get data from mysql by axios
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.