28

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()?

5 Answers 5

30

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Praveen, this may not solve the issue. This is standard way of using redux inside react. What i am looking for is, instead of XYZ componenet, make xyz as a function , which will have access to store via props, and return something. Marco comments make sense.
in my understanding, you are looking for a function which gets invoked each time redux-store changes? And i think your plan is to then import that fn into components and change component when redux-store->Fn->Component. If not then atleast write some pseudo-code in your question so that we can understand what you are trying to do and suggest you how to do. Thanks.
Praveen, in easy words , one line problem statement is 'Accessing redux store inside functions' i.e. how can i access redux store inside normal functions, which are not react Components
user2178209 I have edited answer based on your comment
To describe the problem in more detail, what i was trying is, to capture the user actions in frontend (SPA), and report it to splunk (big data) for business analytics. How it was acheived is below, added the logging information, in the action creator (when user clicks and when reducer had done its work) , wrote a log middleware , binded to redux, and middleware was invoking splunk-logging using HEC token . (basically 90% abstracted solution, very minimal code, and reused the code to save the environment)
|
11

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());
}

Comments

0

The proper place to access the store is through a container, connect is used to connect a container to a component, you cannot connect a random function to it.

There is a logger middleware for redux that you might wan't to take a look at, it does what you're trying to achieve.

To use it, just pass it as a middleware to your store:

import createLogger from 'redux-logger';

const store = createStore(
  reducer,
  applyMiddleware(logger)
);

A more proper way to debug a redux app is to use React Dev Tools, if you use Chrome, I recommend you to use the React Dev Tools Extension. Just install it and use it as a middleware

let store = createStore(reducer, window.devToolsExtension && window.devToolsExtension());

With it, at any given moment you can see the whole state of your store, see the actions being fired and how they affect the store, and even rewind your application by un-doing actions.

8 Comments

Hi Marco, yes, I am using the redux logger for logging the actions / states to redux-storage. that won't serve the purpose. What i want to achieve is to have a simple function access to the store, so that i can use values within a reducer. one of the ways is to directly import the store into JS (anti-pattern) . is there a way to bind a function to the connect() function of redux
@user2178209 It's not exactly clear what you're trying to achieve, why would you need to use store values in a reducer? The reduce already gets the state when an action is fired.
what i meant is , i want to access the values from the store (reducer) inside a function, and that function need to be exposed , to be used by various components.
That's not how Redux works, values from the store are passed to the component only by the container.
And that container, can it be a function or it need to be a component
|
0

Yes. You can attach functions via connect as below;

  const mapDispatchToProps = (dispatch) => {
     return {
       testFunction: (param1) => dispatch(testFunction(param1)),
       testFunction1: () => dispatch(testFunction1())
    };
 };

 export default function connect(mapStateToProps, mapDispatchToProps)(log);

1 Comment

JagKum, where is the log() function in the above code. Like where would i put the code which belongs to log.
-1

redux state can be accessed as prop in a function by using below format.

1:

import { connect } from 'react-redux';

// log accepts logMessage as a prop
function log(props) {
    const { environment, logMessage } = props;
    console.debug('environment' + environment + logMessage ); 
    ....
}

function mapStateToProps(state) {
    return {
        environment : state.authReducer.environment
    };
}

export default connect(mapStateToProps)(log);

How to use log function?

log({ logMessage: "Error message" });

2:

// import redux store 
import { store } from './Store';

function log(logMessage) {
    const currentState = store.getState();
    const environment = currentState.authReducer.environment;
    console.debug('environment' + environment + logMessage); 
    ....
}

1 Comment

connect only works with react components (class or functional ones). It wont work with simple functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.