Home > Software design >  Array Spread Syntax not working as expected on React State Variable
Array Spread Syntax not working as expected on React State Variable

Time:11-15

Hi I'm trying to take some data from my Firebase Firestore and save it to state in my React app. My code is this:

const [firebaseOrders, setFirebaseOrders] = useState([])

useEffect(() => {
    const getOrders = async () => {
      
      const querySnapshot = await getDocs(collection(db, `users/[email protected]/orders`));
      querySnapshot.forEach((doc) => {
        const newOrder = doc.data()
        setFirebaseOrders([...firebaseOrders, newOrder])
      })
  }
    getOrders();
  }, [])

  console.log(firebaseOrders)

I am expecting to get an array of objects with my orders. Instead my array is not saving when I use the spread operator so I end up with just the last item in my array:

Here's a pic of what I get in the console

[{…}]
->0 : {titles: Array(2), timestamp: nt, prices: Array(2), amount: 869.99, amount_shipping: 6.99, …}
length : 1
->[[Prototype]] : Array(0)

[{…}]
->0 : {amount: 78.29, timestamp: nt, titles: Array(2), amount_shipping: 0, prices: Array(2), …}
length : 1
->[[Prototype]] : Array(0)

I feel like I am missing something basic, can anyone help me out?

CodePudding user response:

Modifying state is an asynchronous operation, so doing this in a tight loop (as you do) means that you're overwriting the previous value each time.

Instead, call setFirebaseOrders just once with all results:

setFirebaseOrders(
  querySnapshot.docs.map((doc) => doc.data());
})

Also note that the console.log(firebaseOrders) may not show the correct value, as it likely runs before setFirebaseOrders(...) has run/completed.

If you want to see the orders from the state, show them in components in your UI. If you want to console.log what you get from the database, do so in the callback:

const orders = querySnapshot.docs.map((doc) => doc.data());
console.log(orders);
setFirebaseOrders(orders);
  • Related