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!
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!
Share Improve this question edited Feb 16, 2018 at 9:32 Mayank Shukla 105k19 gold badges162 silver badges145 bronze badges asked Aug 31, 2017 at 7:18 NoceboNocebo 2,0373 gold badges18 silver badges28 bronze badges2 Answers
Reset to default 7Why 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.
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 ;
})