Daniel Thompson
Daniel Thompson

Reputation: 2353

How component is getting data from redux store?

Following along the example async app from the Redux documentation, and I really don't understand how the component AsyncApp has access to the posts that are fetched async.

function mapStateToProps(state) {
 const { selectedSubreddit, postsBySubreddit } = state
  const {
    isFetching,
    lastUpdated,
    items: posts
  } = postsBySubreddit[selectedSubreddit] || {
    isFetching: true,
    items: []
  }
 
  return {
    selectedSubreddit,
    posts,
    isFetching,
    lastUpdated
  }
}

Questions:

1- what is this expression: postsBySubreddit[selectedSubreddit]? Accessing a function with brackets? Does this set up the component with the props posts from const { selectedSubreddit, posts, isFetching, lastUpdated } = this.props

2- They are able to send <Posts posts={posts} /> but where are they getting those posts from in the first place!? Why are they a part of the props!?

Upvotes: 1

Views: 116

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

What is this expression: postsBySubreddit[selectedSubreddit]? Accessing a function with brackets?

No, postsBySubreddit is not a function, its an object basically, and [] (bracket notation) is for accessing the object values by some dynamic key.

Check this snippet:

let obj = {a:1, b:2};
let k = 'b';                  //k will have the property name
console.log('value of b = ', obj[k]);

As per MDN Doc:

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

You are getting confused with Destucturing and Short-Circuit Evaluation, See what exactly is happening there:

const selectedSubreddit = state.selectedSubreddit; 
const postsBySubreddit = state.postsBySubreddit;

const data = postsBySubreddit[selectedSubreddit] || { isFetching: true, items: []}
const isFetching = data.isFetching; 
const lastUpdated = data.lastUpdated; 
const lastUpdated = data.lastUpdated;

Where are they getting those posts from in the first place!?

Those values are getting passed from redux store. mapStateToProps will get the store as first argument and from there we can access any data. We use Provider that will provide the store data to all the connected component.

As per DOC:

Provider makes the Redux store available to the connect() calls in the component hierarchy. Normally, you can’t use connect() without wrapping a parent or ancestor component in <Provider>

Upvotes: 2

Related Questions