简体   繁体   中英

How do i dispatch redux outside provider?

I am trying to save a notification from firebase to redux when the application is on quit.

But I need to do that in app.js, how can I dispatch redux action when I am not even on the component?

Here is what I am trying to do

componentDidMount(){
  messaging().getInitialNotification().then(remoteMessage) => { 
    dispatch(action({
      notification:true,
      data:remoteMessage.data
    }));
  }
}
  
render(){
  return(
    <Provider context={MyContext} store={store}>
      <App />
    </Provider>
  );
}

You can first export your store like

export const store = createStore(
  combineReducers({
    auth: authReducer,
    team: teamReducer,
  }),
  applyMiddleware(thunk),
);

<Provider context={MyContext} store={store}>
  <App />
</Provider>

make sure this is the same store you are passing to the provider

Then you can import this store wherever you want and use it like

import {store} from './index';
import * as actions from './actions';

store.dispatch(actions.getMySolution());

Happy learning!

Edit: As @markerikson said in the comments below, it is not advised to do so until it is really necessary.

So, I will mention one practical use case. let say you want to dispatch an action inside your API call to set loader and unset loader once the API call is completed.

import {store} from './index';
import * as actions from './actions';
import axios from 'axios';

export const get = (params) => {
  return new Promise((resolve, reject) => {
    store.dispatch(actions.setLoading());
    axios
      .get(url)
      .then((data) => {
        store.dispatch(actions.stopLoading());
        resolve(data.data);
      })
      .catch((e) => {
        store.dispatch(actions.stopLoading());
        reject(e);
      });
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM