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.

Sign up to request clarification or add additional context in comments.

2 Comments

It works, thanks! I just wanted to see if there's a smooth option doing it with setState. But this looks a lot cleaner!
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.
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 ;
})

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.