Yoqubxon Xamidoff
Yoqubxon Xamidoff

Reputation: 27

Access variable outside useEffect in React.js

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

Upvotes: 0

Views: 438

Answers (2)

netlorecomment
netlorecomment

Reputation: 156

Move } after useEffect to end of the function for this problem. Next problem is that you are using "await" within "then" try write this code:

const {docs} = await getDocs(collection(db, "orders"))
  const newData = docs.map((doc) => ({
    ...doc.data(),
    id: doc.id,
  }));
  setOrders(newData);
  console.log(orders, newData)

Upvotes: 0

Aurélien
Aurélien

Reputation: 1655

The function fetchPost() should be in your component scope:

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);
    });
  };

// Then, return()...    

}

Upvotes: 1

Related Questions