I would prefer to have a function exposed from a .js
file , within that function I would prefer to have access to the variables in the store.
Snippet of the code : -
import { connect } from 'react-redux'; function log(logMessage) { const {environment} = this.props; console.debug('environment' + environment + logMessage ); .... } function mapStateToProps(state) { return { environment : state.authReducer.environment }; } export default function connect(mapStateToProps)(log);
I have many components, which attach the class through connect
, can I attach functions through connect()
?
Start by importing useSelector from 'react-redux'. Very similar to the useState hook, you will declare a variable at the top of your component and set it equal to the return value of the useSelector function. The useSelector function takes another function as its parameter.
It's simple to get access to the store inside a React component – no need to pass the store as a prop or import it, just use the connect function from React Redux, and supply a mapStateToProps function that pulls out the data you need. Then, inside the component, you can pass that data to a function that needs it.
How does Redux connect() work? The connect() function provided by React Redux can take up to four arguments, all of which are optional. Calling the connect() function returns a higher order component, which can be used to wrap any React component.
React is popular for its ability to write functional components. With the React-Redux release, we can use the Hook API to manage the state without using the higher-order components. Thus, we no longer need to add extra components to the component tree.
Edit 1
Some_File.js
import store from './redux/store.js'; function aFunction(){ var newState =store.getState(); console.log('state changed'); } store.subscribe(aFunction)
I am assuming you have created store and reducers as redux expects.
~~~~~~~~~~~~~~~
Original Answer Starts
This is a sort of hack, I don't know what you are doing so I can't say you should or you should not do it, but you can do it this way. I have copy-pasted some of your code with some modifications.
Class XYZ extends React.Component{ componentWillReceiveProps(props){ //in your case this.props.storeCopy is redux state. //this function will be called every time state changes } render(){ return null; } } function mapStateToProps(state) { return { storeCopy : state }; } export default function connect(mapStateToProps)(XYZ);
Put this component somewhere at top, may just inside provider
, whenever state changes this componentWillReceiveProps
of this component will be invoked.
If you have a pure functional component then you can access the redux state directly like this:
import store from './redux/store'; function getStoreDetails() { console.log(store.getState()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With