Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Redux store in JavaScript function

Is it possible to map redux state to a regular javascript function rather than a React component?

If not, is there another way for connecting redux state to a function? (obviously without explicitly passing it in as a param)

I have tried connecting to a function, but it breaks (I don't have an exact error message. the server just hits an uncaughtException). Since React components can be pure functions, does connect() only work with a class ComponentName extends Component (and the likes)?

The reason I want to do such a thing:

I have an redux action generator, and I want the generator to skip doing an API call if it finds the action's result already in the redux state, but I don't want to have to check state explicitly from every container for every single api call. Does this make sense?

Thanks for any ideas.

like image 489
jacoballenwood Avatar asked May 12 '17 18:05

jacoballenwood


People also ask

Can you connect a function to Redux store?

Creating container componentsThe React Redux connect() API is used for creating container elements that are connected to the Redux store. The Redux store is derived from the topmost ancestor of the component using React Context. If you are only creating a presentational component, you have no need for connect() .

How do I access data from Redux store?

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 do I connect Redux to a function?

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.


1 Answers

connect() comes with react-redux package which is React bindings for Redux. But if you want to interact with Redux state with usual JavaScript you don't need either connect() or react-redux for that. You can directly interact with Redux store with its API.

As an example, if you want to listen to actions you can use subscribe() method as follows and use getState() method to access the state.

let unsubscribe = store.subscribe(function(){
  const state = store.getState();
})

I'm not much clear what you are trying to achieve, but I hope this will help.

Edit:

You can create your store in one file and export it.

store.js

import { createStore } from 'redux'
import reducers from "./reducers";

const store = createStore(reducers)

export default store;

Now you can import store from any other file and use it.

import store from "./store";
like image 106
Tharaka Wijebandara Avatar answered Oct 16 '22 12:10

Tharaka Wijebandara