Reputation: 685
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>
);
}
Upvotes: 0
Views: 93
Reputation: 495
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);
});
});
};
Upvotes: 4