Reputation: 2077
I want to add a value to an array(update its state) its working fine but the item is added to the end of the array. I am trying to call sort() method immediately after updating state. Is there a better method to update the state an sort at the same time.
const UpdateZoom = (scale:number)=>{
if(scale>0)
{
setzoomFactors(zoomFactors =>
[...zoomFactors, scale]);
}
}
Setting state immediately after like below resets the state
setzoomFactors(zoomFactors => zoomFactors.sort())
Is there any way to add and sort at the state at the same time
Upvotes: 1
Views: 523
Reputation: 551
How about setting state after sorting?
const newArray = [...originArray, element];
newArray.sort();
setState(newArray);
Upvotes: 2