I am not able to splice the array – × TypeError: Cannot read property ‘splice’ of undefined

I am having issues with splicing the array. I am trying to splice it to modify the position of elements within that array but it is coming back with an error.

if (e.target !== dragNode.current) {
      setUrls((oldList) => {
        let newList = [...oldList];
        newList.splice(
          params.idx,
          0,
          newList[currentItem].splice(currentItem.idx, 1)[0]
        );
        dragItem.current = params;
        return newList;
      });
    }

Where old list being:

OLD LIST 
(2) ["x", "x"]
0: "x"
1: "x"
length: 2
__proto__: Array(0)

And new list:

NEW LIST 
(2) ["x", "x"]
0: "x"
1: "x"
length: 2
__proto__: Array(0)

Answer

I don’t quite understand what you are trying to do in Line 7 (newList[currentItem].splice(currentItem.idx, 1)[0]).

You are targeting the element with the index of ‘currentItem’ and apply splice on it. This does not work since you are targeting a single element inistead of an array.

Leave a Reply

Your email address will not be published. Required fields are marked *