Use select effect in normal function/eventChannels
Asked Answered
O

1

9

I am using redux sagas event channel. I have a specific use case where i want to getStore state when event gets triggered as eventChannel is not generator function i am not able to use select effect of redux sagas. Any other way to achieve this ?

I had also tried to import store and use store.getState() but i am getting undefined as saga file is imported before store gets initialized.

function subscribe(socket) {
    return eventChannel(emit => {
        socket.subscribe(listenerTopic, {qos: 1});
        socket.on('reconnection', () => {
            // i need to fetch latest unread message, for that i need to get timestamp
           // for last message received which is in store so the command will be to 
         // send sinceDate i.e last message timestamp and untilDate that is currentDate
   })
}
Outstand answered 5/4, 2017 at 16:11 Comment(2)
The solution will likely involve moving some logic from the eventEmitter function to the saga taking its actions. Can you share some code so that we can see what the eventEmitter / saga taking its events are doing ?Schwerin
My use case is I need to fetch latest unread message when connection is revived, for that i need to get timestamp for last message received which is in store so the command will be to send sinceDate i.e last message timestamp and untilDate that is currentDateOutstand
I
2

One possible solution would be to use redux-saga channel feature. The idea would be to push an event into the channel each time a socket event occurs. At the same time you have another saga listening for events on the channel and reacts accordingly. Because the listening part is a saga, you can use common saga effects like select.

Your code could probably look like this:

import { channel } from 'redux-saga'
import { select } from 'redux-saga/effects'

const socketChannel = channel()

function subscribe(socket) {
  return eventChannel(emit => {
     socket.on('reconnection', () => {
       socketChannel.put({ type: RECONNECTION })
     })
  })
}

export function* watchSocketChannel() {
  while (true) {
    const action = yield take(socketChannel)

    if (action.type === RECONNECTION) {
      const lastMessageTimestamp = yield select(selectors.getLastMessageTimestamp)
      ...
    }
  }
}

I hope this will help you.

Involucrum answered 8/4, 2017 at 15:37 Comment(1)
What about listener function which returns something in callback like react-native BackHandler BackHandler.addEventListener('hardwareBackPress', return true/false); } How can I read state data and depending on it decide return true or false?Aureliaaurelian

© 2022 - 2024 — McMap. All rights reserved.