0

Is there a pattern or technique we can use for handling events in Recoil?

In Saga we could use the emit method and create stream of data.

Ive been trying to wrap my mind around how something like this can be achieved in Recoil.

For ex scanning for bluetooth connected devices.

 manager.onStateChange(state => {
      const enableScanning = state === State.PoweredOn

      if (enableScanning) {
        manager.startDeviceScan(
          null,
          { allowDuplicates: false },
          (error, scannedDevice) => {
            if (error) {
              return
            }
            if (scannedDevice !== null) {
              //HERE WE NEED TO HANDLE THE ADDITION OF THE DEVICE TO A LIST
            }
          }
        )
      }
    }, true)

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
  • The comment says that you want to "handle" the addition of a device to "a" list. Which list? Does that list live inside a recoil atom or is it react independent? What does "handle" mean? Update that list, update components, trigger server calls? – Johannes Klauß Apr 03 '21 at 12:57
  • Im comparing like saga and redux, so handle would mean in that case add it the the redux store. In this case add it to an atom - then ideally update the component UI. – Sten Muchow Apr 05 '21 at 15:06
  • So is the code you shared in a react hook or life cycle? Then you can just set it inside that callback. – Johannes Klauß Apr 05 '21 at 16:01
  • No I get that, ideally this is a helper fiel where i can invoke the method to listen and then it will update the recoil state for me outside the scope of a component. This obvisouly has issues as there is not a real api for doing this outside the scope of recoil in a component. Im using a version of this RecoilExternalStatePortal which does it but has caveats – Sten Muchow Apr 06 '21 at 13:28
  • Recoil isn't designed to be used outside of the react scope. What speaks against having the manager inside a react hook or component? You can also check https://github.com/luisanton-io/recoil-nexus for accessing the recoil state outside of react – Johannes Klauß Apr 07 '21 at 10:45
  • Thanks im using a similar component i built myself based on a ticket in the recoil repo. Thanks for the discussion. – Sten Muchow Apr 07 '21 at 13:45

1 Answers1

1

I think what you are looking for is useRecoilCallback. It allows you to access all states (snapshot) without being part of a re-render life cycle. Also, once you have that snapshot, there is an API that allows you to filter changed states,

for (const node of snapshot.getNodes_UNSTABLE({ isModified: true })) {
        if (atomKeys.length === 0 || atomKeys.includes(node.key)) {
            console.debug(node.key, snapshot.getLoadable(node).contents);
        }
    }

Even though, it is not an event handler or raise event, but you can invoke it periodically and monitor the state changes.

Henning Hall
  • 1,297
  • 2
  • 11
  • 31
tigerpaw
  • 135
  • 4