#102·swapy

[Question] How do I update state with the new order in React?

Author: MagnusFischerCreated Dec 14, 2024Updated Jul 21, 2025

Excuse my question, I hope this is okay.

In the React (Dynamic) example from the docs, changing the order around doesn't actually change the order of the items in the items state.

I've been trying to implement Swapy in a project I'm working on that uses Zustand to provide a global store. I have been trying to update the Zustand state inside swapyRef.current.onSwapEnd() but that results in Swapy using a stale state, which causes all kinds of issues.

I'm probably missing something here, so I hope someone out there has already figured this out :-)

This is my Zustand action:

javascript
arrangeBlocks: (configuratorId, stepId, blocks) => {
  set(
    (state) => {
      const newConfigurations = state.configurations.map((config) =>
        config.id === configuratorId
          ? {
              ...config,
              steps: config.steps.map((step) =>
                step.id === stepId
                  ? {
                      ...step,
                      blocks,
                    }
                  : step
              ),
            }
          : config
      )

      return {
        configurations: newConfigurations
      }
  })
}

This is where I call the action, inside a useEffect() where the swapy instance also gets initialized

javascript
swapyRef.current.onSwapEnd((event) => {
  const newItemOrder = event.slotItemMap.asArray.map((slotItemMap) => slotItemMap.item)
  //step.blocks is provided by the global state from Zustand
  const reordered = [...step.blocks].sort((a, b) => {
    return newItemOrder.indexOf(a.id) - newItemOrder.indexOf(b.id)
  })
  arrangeBlocks(configuratorId, stepId, reordered)
})

I hope someone smarter than me is able to help me solve this. Please let me know if you need more information.