问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/57338307/redux-saga-channel-pass-in-variable-for-api-call