Skip to content
Advertisement

Connecting actions to store outside a component?

So let’s suppose I have a store, with a redux-thunk middleware in it. I created the store and exported it like this:

import myOwnCreateStoreMethod from './redux/createStore';
export const store = myOwnCreateStoreMethod();

I can now access it anywhere in my app. But what if I want to dispatch an action from anywhere? I have them declared e.g. in myAction.js:

export const myAction = () => (dispatch, getState) =>
    dispatch({ type: 'SOME_TYPE', payload: ... })

Now I can import them and connect to my store/component like this:

import * as actions from './myActions.js';

const MyComponent = () => <div>Hello World</div>;
const mapStateToProps = () => ({});
export default connect(mapStateToProps, actions)(MyComponent);

My question is – what if I do not have a component and still want to dispatch actions declared like the one above?

Advertisement

Answer

You can dispatch actions from the store directly

import store from './myStore';
import { myAction } from './myAction';    

store.dispatch(myAction());

Redux is a library by itself.

It has nothing to do with React, they just work well together based on React single source of truth and Redux one global store as the state of our application.

You can use redux in every JavaScript application.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement