Access redux without react Access redux without react reactjs reactjs

Access redux without react


This is what I do (after creating my store):

export const dispatch = store.dispatch

Then you can call dispatch from anywhere in your code (although I pretty much just do it from event handlers).

If you use Redux-Saga to manage your flow-control, you only rarely need to use dispatch, aside from event handlers for direct user inputs, because it wraps dispatching in its put API.


I don't think you should be listening to changes directly from the store, but you would need it in order to dispatch actions.

Listening to changes

In redux the natural place for you to call this kind of logic would be from the action that dispatches the change in the field.

export function updateSomeField(value, field) {    fieldValidator.validate()    return { type: ActionTypes.UPDATE_SOME_FIELD, field: field, value: value }}

fieldValidator can hold a reference to the store in order to get the state he needs in order to perform his logic with store.getState(), or get that data from the action as a parameter (with the help of async actions):

export function updateSomeField(value, field) {    return (dispatch, getState) => {        fieldValidator.validate(getState.myScreen.fields)        dispatch({ type: ActionTypes.UPDATE_SOME_FIELD, field: field, value: value })    }}

Getting the store

As soon as you create it, you can just provide it to anyone who needs it.You can either do it by initializing a singleton

let store = createStore();FieldValidator.setInstance(new FieldValidator(store));// FieldValidator.jsclass FieldValidator {    ...     static _instance = null;    static getInstance() {        return FieldValidator._instance;    }    static setInstance(fieldValidator) {        FieldValidator._instance = fieldValidator;    }    ...}

Or by injecting a member

let store = createStore();fieldValidator.store = store;