I am trying to fetch data as soon as page loads using useEffect(), but the problem is I don't know where to declare stateful const [orders, setOrders] = useState([]); when I put it above main function ( trying to make it global ) I get error saying React useState cannot be called top level. When I move it inside the function I cannot access it from fetchdata() function. I have to use setOrders from inside fetchdata() What is the proper way to do it ?
function ActiveOrders () {
const [orders, setOrders] = useState([]);
useEffect(()=>{
fetchPost();
}, [])
}
const fetchPost = async () => {
await getDocs(collection(db, "orders"))
.then((querySnapshot)=>{
const newData = querySnapshot.docs
.map((doc) => ({...doc.data(), id:doc.id }));
setOrders(newData);
console.log(orders, newData);
})
}
Error I am getting : 'setOrders' is not defined
'orders' is not defined