使用eventChannel从Firestore获取实时数据

时间:2020-08-13 07:32:59

标签: reactjs react-native redux redux-saga saga

我想在React与Firestore中同步我的数据,每次更改某些数据时,我都希望对我的数据进行更新/刷新。

要获取我拥有的数据:

function*  syncCustomers() {
    try {
        const response = yield call(fireBaseBackend.getCustomersAPI);
        yield put(loadCustomers(response));
    } catch (error) {
        yield put(customerError(error));
    }
}

我的getCustomersAPI在哪里:

getCustomersAPI = () => {
    return new Promise((resolve, reject) => {
        firebase.firestore().collection("customers").onSnapshot((snap) => {
            let documents = [];
            snap.docs.forEach(doc => {
                let result = doc.data();
                result.uid = doc.id;
                documents.push(result);
            });
            resolve(documents);
        });
    });
};

这可以实时获取我的数据:

function* usersChannelSaga () {
    try {
        while (true) {
            const response = yield call(fireBaseBackend.getCustomersAPI);
            yield put(loadCustomers(response));
        }
    }
    catch (error) {
        yield put(customerError(error));
    }
}

但是我想为此使用eventChannel。这需要如何实施? 我尝试过:

function* usersChannelSaga () {
    const channel = eventChannel(emit => fireBaseBackend.syncCustomers(emit));
    try {
        while (true) {
            const data = yield take(channel);
            yield put(loadCustomers(response));
        }
    }
    catch (error) {
        yield put(customerError(error));
    }
}

syncCustomers在哪里:

  syncCustomers(emit){
        return firebase.firestore().collection("customers").onSnapshot(emit);
    }

有人知道如何解决这个问题吗?

0 个答案:

没有答案