I need to update an state of objects using prevState from useState().
I have this callback that updates the data state maintaining all previous addresses:
onSuccess: (address) =>
setData((prevState) => {
return [...prevState, address];
}),
But it is sorting each time I call this callback, for ex:
The first time this callback is called, the previous state is [], the second time is
[
{address: 'England London Islington', miles: '15.81', kilometers: '25.45'}
]
The third time it continues the right way, with Islington at index 1 and Lambeth at index 0:
[
{
"address": "England London Lambeth",
"miles": "14.29",
"kilometers": "22.99"
},
{
"address": "England London Islington",
"miles": "15.81",
"kilometers": "25.45"
}
]
But after that the prevState sorts in a different way the elements:
[
{
"address": "England London Westminster",
"miles": "13.83",
"kilometers": "22.25"
},
{
"address": "England London Islington",
"miles": "15.81",
"kilometers": "25.45"
},
{
"address": "England London Lambeth",
"miles": "14.29",
"kilometers": "22.99"
}
]
As you can see, Islington is at the middle of Lambeth and Westminster, and I don't it that way, I need to keep the sorting so I can use in a list, but I have no idea how to keep it.
CodePudding user response:
You can use the .sort() build in function to sort the array as you like:
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
Reference: MDN Array.prototype.sort()
CodePudding user response:
Object de-structuring and re-assigning will lead to unexpected results and data transitions. I would recommend to avoid that approach as a whole
One potential way to go about this would be to the data value itself in the udpateData hook
so for example:
const [data, setData] = useState([{val: 1}, {val: 2}])
...
...
onSuccess: (address) => {
setData(data.push(address)) // Assuming address is an object of same type as data array
}
Doing it this way would also ensure that information is stored as it was entered, hence avoiding the need for sorting