Is there a way to use createAsyncThunk with Firebase listeners, for example firestore.collection.onSnapshot?
It may not work because the way onSnapshot works (it's a listener that receives data and fires a callback every time firestore updates and it returns a function that unsubscribes the listener). I tried implementing createAsyncThunk but couldn't figure it out.
Here's my current thunk implementation which does work:
const listenerUnsubscribeList = [];
export function fetchProjects() {
return dispatch => {
dispatch(fetchProjectsPending());
const unsubscribe = firestore
.collection('projects')
.onSnapshot(
snapshot => { dispatch(fetchProjectsFulfilled(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })))) },
error => { dispatch(fetchProjectsError(error)) },
);
listenerUnsubscribeList.push(unsubscribe);
}
}
Here's my attempt at createAsyncThunk which does not work. I'm getting database/fetchProjects/pending and database/fetchProjects/fulfilled but payload is undefined
const listenerUnsubscribeList = [];
export const fetchProjects = createAsyncThunk(
'database/fetchProjects',
async (_, thunkAPI) => {
const unsubscribe = await firestore
.collection('projects')
.onSnapshot(
snapshot => { return snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })) },
error => { return error },
);
listenerUnsubscribeList.push(unsubscribe);
}
);