Jordan
Jordan

Reputation: 55

How do I pass redux store from one component to another?

I'm trying to pass information from Redux store into several table components like this:

<Table timelogData={store.getState()} />

When I try to console.log this data inside the table component directly, the component will render and the console.log will work

console.log(this.props.timelogData.)

However, if I try to go deeper into the tree, e.g.

console.log(this.props.timelogData.userProfile)

I receive "TypeError: Cannot read property 'userProfile' of undefined" Even though I receive the TypeError, the console.log will complete successfully strangely. It's able to access it through the console, but React doesn't like it.

How do I correctly pass Redux store into another component with the ability to access data further down the tree?

Upvotes: 2

Views: 1947

Answers (3)

KT-mongo
KT-mongo

Reputation: 2212

This console.log(this.props.timelogData.userProfile) doesn't work because you probably haven't added the property from mapStateToProps. To answer your question how to pass store to different components, assuming you have used Provider (usually within the index.js file)

render(
   <Provider store={store}>
       <App/>
   </Provider>,
  document.getElementById('root')
)

then any component is 'hooked' to your store state, as long you connect the relevant component.

const mapStateToProps = state => ({someRandomProp: state.someValue})
export default connect(mapStateToProps)(ComponentThatNeedsYourStore) 

But I would suggest to go back and read the official documentation.

Upvotes: 0

David O&#39;Regan
David O&#39;Regan

Reputation: 2674

You need to leverage mapStateToProps in your components and not try to pass down the store.


function mapStateToProps(state){
    return {
        nameAsProps: state.username,
    }
}

See: https://medium.com/ovrsea/mapstatetoprops-and-why-you-may-not-need-mapdispatchtoprops-as-a-beginner-dd012a3da5e6

Upvotes: 0

mfreitas
mfreitas

Reputation: 2405

You don't pass down your store to your components. You should use react-redux which provides react bindings to connect your components to your redux store. Familiarize yourself with the concepts through their documentation.

Make sure you understand the basic concepts like the difference between presentational components and containers, action creators, reducers and how to map your state to component props.

Upvotes: 4

Related Questions