2

I asked myself if there is a clean, proper way to swap two objects in an array using setState. This is what I currently do:

export function moveStepUp(index) {
    if(index > 0){
        let currentStep = this.state.stepsData[index];
        let stepAbove = this.state.stepsData[index - 1];

        this.setState((prevState) => ({
            stepsData: prevState.stepsData.map((step, i) => {
                if(i === index - 1)
                    return {
                        ...currentStep,
                        position: i
                    };
                if(i === index)
                    return {
                        ...stepAbove,
                        position: i
                    };

                return step;
            })
        }), () => console.log(this.state.stepsData));
    }
}

This code is working, but I thought there might be a better solution. It seems like too much lines of code for such a simple task. Thanks!

2 Answers 2

7

Why not simply swapping two array values by using a third variable if you know the element index. First copy the array in another variable, swap two array values, then use setState to update the state value.

Like this:

this.setState(prevState => {
    let data = [...prevState.data];

    let temp = data[index-1];
    data[index-1] = data[index];
    data[index] = temp;

    return { data };
})

Instead of spread operator, you can use any other way to create a copy of array.

2
  • It works, thanks! I just wanted to see if there's a smooth option doing it with setState. But this looks a lot cleaner!
    – Nocebo
    Commented Aug 31, 2017 at 7:28
  • 1
    glad it helped you :) one suggestion always try to perform the calculation first then use setState to update the state value, instead of putting the logic inside setState. Commented Aug 31, 2017 at 7:32
1

In react hooks you can use this, this works for me

const [array,setArray]= useState([]);
setArray(array => {
    let data = [...array];
    let temp = data[j];
    data[j] = data[j+1];
    data[j+1] = temp;
    console.log(data);
    return data ;
})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.