'How to perform both a spread "operation" AND a callback function with useState in React

I am using functional components instead of class-based components. I have a state of hikes that is an array of objects and whenever I want to add a new hike to that array, I invoke the following line:

setCoors((coors=> [...coors, newCoor]))

But I also NEED to have the state callback function implemented. This is what Ive tried and it "sort of" works.

setCoors({coors:[...coors, newCoor]}, ()=>{console.log(coors)} )

But this is what I get back:

{
   coors:[
      0: {lat: 37.00, lng: -100.12},
      1: {lat: 88.00, lng: 76.12},
   ]
}

But i dont want my coor state to be an object...I need it to be an array like this:

{
   [
      0: {lat: 37.00, lng: -100.12},
      1: {lat: 88.00, lng: 76.12},
   ]
}

I can probably destructure the object to get what i want but I wanna know if there is an actual solution to this with setState. Does anyone have an idea of achieving this while also implementing a callback function? Thank you in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source