dace
dace

Reputation: 6363

How to get state from the store in a container?

I'm a little confused as to how to get state from within a container. I'm fine with mapping dispatch to props & dispatching actions.

In the docs it states store.getState(), but do I first need to mapStateToProps in order to call this.props.getState() or can I simply call store.getState() anywhere in my container and I'll have access to the store passed through my Provider?

Upvotes: 2

Views: 2389

Answers (2)

markerikson
markerikson

Reputation: 67469

The first argument to the connect() function is an optional function known as mapStateToProps. If you provide a mapState argument, the wrapper component generated by connect() will automatically call your mapState function every time the store is updated, and pass in the new state. Your mapState function should then extract whatever pieces of data the connected component needs, and return them. (mapStateToProps is really just a specific usage of the concept known as a "selector" function - see Computing Derived Data of using selectors).

Your own component code should never access the store directly, but rather just accept the props that are passed in. See Redux FAQ.

Upvotes: 3

Sidharth Mehra
Sidharth Mehra

Reputation: 1

So this is the flow in Redux from what I have understood. You call an action from your container from say an onClick method which in turn gets reduced and returns the copy of the state. This copy of the state is available in your mapStateToProps function which will set your props object to the new state object. Your render function is going to utilize this new updated prop object and render if there is any update to the state.

Hope this resolves your query.

Check out my github repo where I have made a simple Courses app to add/manage courses. https://github.com/sidharthmehra/ReactReduxApp

Upvotes: 0

Related Questions