Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Redux dispatch action from root component?

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;
like image 450
Groovietunes Avatar asked Nov 20 '16 01:11

Groovietunes


People also ask

Is it possible to dispatch an action without using mapDispatchToProps?

Without mapDispatchToPropsNotice that the component receives a dispatch prop, which comes from connect() , and then has to use it directly to trigger the actions.

Can we dispatch action from reducer?

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.


2 Answers

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.

like image 186
farwayer Avatar answered Sep 19 '22 13:09

farwayer


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

like image 28
Kalob Porter Avatar answered Sep 20 '22 13:09

Kalob Porter