'why useState return empty array in react.js? [duplicate]

I am trying to receive an array from useState when I click the first time on submit ,the usestate return an empty array and this make a probleme ?

const [order,setOrder] = useState([]);

const submit = (e) => {

 var NU =document.querySelector('#orderDesignation').value;
  var d =document.querySelector('#orderPrix').value;
   var p = document.querySelector('#origin').value;

     var q =document.querySelector('#orderQuntite').value;
    var t =document.querySelector('#orderPrixHT').value;


const  s = { orderDesignation: "d" ,orderPrix: "p" ,orderQuntite: "q" ,orderPrixHT:"t" }

console.log("s -->",s);

//s --> Object { orderDesignation: "dss", orderPrix: "1", orderQuntite: "3", orderPrixHT: 2 }

setOrder(order => [...order,s] );
 
console.log("order =",order);   //    order = Array[]   empty !!!! ?

}
      


Solution 1:[1]

Because setOrder command is not a immediate command ,React may delay it and because your console.log is in next line in same function, it will returns the default value of order that is empty array.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Hesam