How to tie emitted events events into redux-saga?

后端 未结 5 652
情书的邮戳
情书的邮戳 2020-12-28 18:45

I\'m trying to use redux-saga to connect events from PouchDB to my React.js application, but I\'m struggling to figure out how to connect events emitted from PouchDB to my S

5条回答
  •  旧巷少年郎
    2020-12-28 18:59

    We can use eventChannel of redux-saga

    Here is my example

    // fetch history messages
    function* watchMessageEventChannel(client) {
      const chan = eventChannel(emitter => {
        client.on('message', (message) => emitter(message));
        return () => {
          client.close().then(() => console.log('logout'));
        };
      });
      while (true) {
        const message = yield take(chan);
        yield put(receiveMessage(message));
      }
    }
    
    function* fetchMessageHistory(action) {
      const client = yield realtime.createIMClient('demo_uuid');
      // listen message event
      yield fork(watchMessageEventChannel, client);
    }
    

    Please Note:

    messages on an eventChannel are not buffered by default. If you want to process message event only one by one, you cannot use blocking call after const message = yield take(chan);

    Or You have to provide a buffer to the eventChannel factory in order to specify buffering strategy for the channel (e.g. eventChannel(subscriber, buffer)). See redux-saga API docs for more info

提交回复
热议问题