Home > Software engineering >  Access variable outside useEffect in React.js
Access variable outside useEffect in React.js

Time:01-05

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

CodePudding user response:

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

}

CodePudding user response:

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)
  • Related