1

I am trying to unshift an array value with existing array by using spread operator approach. getting error. any one help me to get correct approach?

here is my code :

uploadedFiles : [...state.uploadedFiles.unshift( (<fileActions.UploadFileSuccess>action).payload ) ]

getting an error as :

The Number is not array type

Thanks in advance.

1
  • Two quick notes: 1. I'm going to guess from the name that state is a React state object. If so, you must never directly modify it (which unshift does). 2. ... isn't an operator. :-) Commented Apr 5, 2019 at 9:43

2 Answers 2

5

unshift mutates the array and returns the new length of the array, which is a number, and that can't be spreaded. Your code boils down to:

 [...state.uploadFiles.length]

Now to do that in an immutable and correct way, don't use unshift, just add the element to the array before spreading the previous version:

 [action.payload, ....state.uploadFiles]
Sign up to request clarification or add additional context in comments.

2 Comments

the try i made to add the new object as first member of array. as like your suggestion it puts the new member as last one...
@user2024080 - No, the above definitely makes action.payload the first entry in the resulting array.
3

Array#unshift returns the new length of the array.

You need just to take the item without spreading.

uploadedFiles: [(<fileActions.UploadFileSuccess>action).payload, ...state.uploadedFiles]

If you like to update state.uploadedFiles, you could unshift in advance.

state.uploadedFiles.unshift((<fileActions.UploadFileSuccess>action).payload);

uploadedFiles: [...state.uploadedFiles]

Comments

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.