Access to contraction without reaction

I need access to the store (to send and monitor) without using React components. I searched a couple of hours without any results.

This is true. I created a repository in the root of the application:

import { Provider } from 'react-redux' import createStore from './state/store'; let store = createStore(); ReactDOM.render( <Provider store={store}> <App> </Provider>, document.getElementById('root') ); 

I am happy to use the connect function offered with react-redux when I need to add actions or listen for state changes in a component, but when I want to install some logic outside the component (basically sending), I get stuck.

In short, I want to check one field. I want to create a validation.js file where I can listen for changes from the repository, run validation logic and then send the action with a possible error.

As for the store, it is not global, and I do not use the React component. What is the way to get the store to listen to changes and post actions?

Thanks in advance.

+8
javascript reactjs redux
source share
2 answers

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

export const dispatch = store.dispatch

You can then call dispatch from anywhere in your code (although I pretty much only do this from event handlers).

If you use Redux-Saga to control the flow, you rarely need to use dispatch , except for event handlers for direct user inputs, as it completes the send to its put API.

+5
source share

I do not think that you should listen to the changes directly from the store, but you will need it to send actions.

Listening to changes

In redux natural place where you could name such logic would be from action , which sends the change to the field.

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

fieldValidator can contain a reference to the store to get the state it needs, to execute its logic using store.getState() , or to get this data from the action as a parameter (using asynchronous actions)

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

Retrieving Storage

Once you create it, you can simply provide it to everyone who needs it. You can do this by initializing singleton

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

Or by typing a member

 let store = createStore(); fieldValidator.store = store; 
+2
source share

All Articles