Alejandro Morales
Alejandro Morales

Reputation: 63

Uncaught TypeError: Cannot add property 0, object is not extensible || using Firestore, Redux, createAsyncThunk

I am getting that error when trying to subscribe to realtime updates on firestore via onSnapshot(), using it inside the async function of createAsyncThunk with redux react tools.

The function doesnt wait for the forEach to finish. I have tried a for of loop, but does not work with onSnapshot.

This is my createAsyncFunction.

export const getAuctions = createAsyncThunk(
    'auctions/getAuctions',
    async () => {
        const auctionRef = collection(db, "auctions");
        const fetched = [];
        onSnapshot(auctionRef, (querySnapshot) => {
            for (const doc of querySnapshot.docs) {
                fetched.push(doc.data());
            };
        })
        return fetched
    }
)

This is called from a dispatch() inside a useEffect one time when the app loads. Any idea?!

Thank you

Upvotes: 1

Views: 237

Answers (1)

markerikson
markerikson

Reputation: 67489

There's three problems here:

  • onSnapshot runs long after this async thunk returns, not during the thunk. So, you're actually returning an empty array "now", and it won't have any data inside.
  • When the onSnapshot does run, it tries to mutate the fetched array... but that array reference has already been added into the Redux state and frozen by Immer. So, the JS engine is throwing an error because you can't mutate a frozen array.
  • On top of that, onSnapshot can apparently run multiple times, whereas a thunk is intended to run once (per time that you dispatched it).

I'm not familiar with Firebase's API, but you should try to use something that returns data "now", along the lines of (fake code): const data = await collection(db, "auctions").get()

Upvotes: 2

Related Questions