How to Fetch Redux Data ?
Our whatsapp analogy says to read/fetch data of any components
from STORE (group), it needs to be CONNECTED.
REACT-REDUX provides really easy way to connect to THE STORE...
Step 1: Import connect() method from react-redux.
import { connect } from 'react-redux'
Step 2: connect the component which wants STORE data.
export default connect(mapStateToProps, mapActionToProps)(OurComponent)
But wait a minute what are these mapStateToProps, mapActionToProps ?
Let’s Understand via analogy...
How our neighbourhood supermarket/store help us get the required item in easy way:
1. They employ helpers to help us get the right item.
2. They have sign boards hanging, for us to reach at right row to fetch required item.
3. They provide scanners to get right weight and price.
POINT TO NOTE:
These helper tools don’t do anything by themselves, Once you visit the STORE,
you have to summon them to avail the services.
(sounds like dark lord summons the spirits to do the work… scary... :))
Same as our neighbourhood store, REDUX STORE also provides two helper methods called
1. mapStateToProps.
2. mapActionToProps.
And just like normal store, these helper methods do not do anything without summoning them i.e.
1. you have to call them (override them) in your component and
2. tell them explicitly what do you want.
By adding below code in our component , we are summoning mapStateToProps
const mapStateToProps = () => {
anyVarName: state.componentXData
}
And what helper is doing:
1. Mapping some store state data to local variable.
2. Adding that local variable into component props.
3. And hurrey!!!! we have access to the required data via props.anyVarName
anywhere in the component.
In essence mapStateToProps as name suggests take explicitly stated state
data from THE STORE and adds them into component props.
i.e. In our above example we are accessing componentXData from THE STORE and
adding it into props variable named anyVarName.
which is accessible within OurComponent as props.anyVarName.
Isn’t it awesome…
To conclude:
If you want to get any STORE data in you component, do below
1. Connect() the component
1. Connect() the component
2. Summon(override) mapStateToProps
3. And boom you have data as props in your component
It can’t be made more easier then that….
You must be thinking out loud, how can I conclude...
we still have to demystify mapActionToProps…
Yes we will, that is our next topic Creating and Deleting THE SM STORE Data
No comments:
Post a Comment