0

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

0

2 Answers 2

1

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()...    

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx! Fixed and working!
Good to read that! If your issue is closed, please mark it as answered.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.