Redux-Saga Channel pass in variable for API call
Asked Answered
G

1

1

Summary

I'm using redux-saga-firebase and to listen for changes in Firestore and I want to pass in a variable from my redux store to my watcher function. I'm new to redux so I'm having some trouble. I think I should use a selector but I'm not 100% how to do so. I'm also open any other solutions!

Code

Watcher Saga

export function* watchSquadChannel() {
  const userData = "345fgr45gdgdfdfe";
  try {
    yield put(syncSquadLoading());
    const channel = RSF.firestore.channel(
      `data/${userData}`,
      "document"
    );
    while (true) {
      const response = yield take(channel);
      const {
        _data: {
          event: { data }
        }
      } = response;
      yield put(syncSquadSuccess(data));
    }
  } catch (error) {
    yield put(syncSquadFailure(error));
  }
}

Data I want to pass in

I want to pass in userData so I can listen only for changes in the document named with that user's ID. userData is stored in my redux store under user object. data structure = state.user.userData

Thanks in advance for your help!

Glyco answered 3/8, 2019 at 12:28 Comment(0)
P
2

Yep you're correct, you need to use a selector. If your userData is ready to go in your store you're most of the way there - you just need to use the select effect in your saga to pull it out:

const userData = yield select(getUserData)

That getUserData is a selector function - it takes your top level Redux state object as input (aka the store), and returns the piece of information you need. I don't know the shape of your state object, but the selector will end up looking something like this:

const getUserData = state => state.foo.bar.userData

If you're not already it's good practice to always use a selector any time you need to dip into your store, whether that's from a saga or when connecting to state in components. Your selectors can act as a consistent interface between your store and the rest of the app. It's worth using a helper library like reselect to build up your library of selectors.

Paresh answered 3/8, 2019 at 12:44 Comment(1)
@bzlight, I think this is what you need. ;)Deandra

© 2022 - 2024 — McMap. All rights reserved.