How to Remove an object from a useSprings object in React?

49 Views Asked by At

I'm gonna say first that i'm aware this question has been asked before here.

The solution there didn't help at all, and research on google resolved nothing either.

I have the following useSprings object:

const fn = (order, down, originalIndex, curIndex, y) => index =>
  down && index === originalIndex
    ? {
        y: curIndex * 100 + y,
        scale: 1.1,
        zIndex: "2",
        shadow: 15,
        immediate: n => n === "y" || n === "zIndex"
      }: {
        y: order.indexOf(index) * 100,
        scale: 1,
        zIndex: "0",
        shadow: 1,
        immediate: false
      };

  const [items, setItems] = useState(["a",'b','c','d']);
 // This represents the item order

const [springs, setSprings] = useSprings(order.length, fn(items.map((_, index) => index))); // Create springs, each corresponds to an item, controlling its transform, scale, etc.

Now i want to remove an element from the springs array. That's how i tried to do it (and failed):

function deleteFirstItem () {
    setItems(items.filter((_, index) => index !== 1));
    setSprings(order.length, fn(order)); // I've understood I'm supposed to just update the ```items``` array, but it didn't work so I tried to add this line. Still didn't work.
    }

The problem is that the function doesn't work and the array springs remains the same.

You can see the full code in CodeSandbox

1

There are 1 best solutions below

1
On

We can try this, first create the new order and and new springs array then, we update the order state with the new order using setOrder and after this we update the springs state by directly passing the new springs array to setSprings.

function deleteFirstItem() {
  const newOrder = order.filter((_, index) => index !== 1);
  setItems(items.filter((_, index) => index !== 1));

  const newSprings = newOrder.map((_, index) => fn(newOrder)(index));

  setOrder(newOrder);
  setSprings(() => newSprings);
}