I'm trying to use firebase with React-Native / Redux I need to dispatch an action every time a user signs in or signs out. How can I dispatch an action from the root component?
class App extends Component {
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// Dispatch Action here
} else {
// Disptach Action here
}
});
}
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<Router />
</Provider>
);
}
}
export default App;
Without mapDispatchToPropsNotice that the component receives a dispatch prop, which comes from connect() , and then has to use it directly to trigger the actions.
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
class App extends Component {
constructor() {
this.store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
}
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.store.dispatch(...);
} else {
this.store.dispatch(...);
}
});
}
render() {
return (
<Provider store={this.store}>
<Router />
</Provider>
);
}
}
export default App;
And do not make any side effects inside render()
function. It must be pure function.
Use the redux connect
and mapDispatchToProps
... find the documentation here. Connect will still work with the root component. Then in your componentWillMount
you can reference the action from your components props passed to it via connect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With