简体   繁体   中英

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

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

}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM