export interface mensajes{
user:any
msg:any
day:any
time:any
}
const [msgArray, setMsgArray] = useState <msgX[]> ( [])
setMsgArray([...msgArray, {user:props.email,msg:mensage, day:date.getDate() "-" date.getMonth() 1 "-" date.getFullYear() , time:date.getHours() ":" date.getMinutes()} ])
that's the way to add a component at the end of the array. But how is it possible to add the component in the initial part of the array?
I need that
{user:props.email,msg:mensage, day:date.getDate() "-" date.getMonth() 1 "-" date.getFullYear() , time:date.getHours() ":" date.getMinutes()}
is positioned at the first element and not at the end
CodePudding user response:
You just, well, put it at the start:
setMsgArray([{/* your new object here */}, ...msgArray])
Instead of putting it at the end, like:
setMsgArray([...msgArray, {/* your new object here */}])
CodePudding user response:
If the next state value depends on the previous value, it is recommended to use functional updates.
Spread syntax (...) allows an iterable such as an array expression to be expanded in places.
here I created an example so you can observe and play
https://codesandbox.io/s/cool-lichterman-3sxm3?file=/src/App.tsx
