Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access store in second component in react-redux

I have a single component App.js where I trying to save state using redux. In index.js where I set store for only <App /> component.

index.js

let store = createStore(scoreReducer);

ReactDOM.render(
  <Provider store={store}><App /></Provider>,
  document.getElementById("root")
);
registerServiceWorker();

I have this method in App.js to map state to props which is available inside App.js.

App.js

function mapStateToProps(state) {
  return { score: state.score, status: state.status };
}

Everything is well so far, now I am not sure how to access { this.props.score} in another component ?

What changes I need to do in index.js and second component if I want to access {this.props.score} in another component ?

like image 595
N Sharma Avatar asked Jun 18 '17 17:06

N Sharma


People also ask

How do you access the store in react Redux?

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.

Can you have two Redux stores?

As with several other questions, it is possible to create multiple distinct Redux stores in a page, but the intended pattern is to have only a single store. Having a single store enables using the Redux DevTools, makes persisting and rehydrating data simpler, and simplifies the subscription logic.


1 Answers

When you are using Provider any component that is children of the Provider Higher Order Component can access the store properties though the use of connect function.

So you can add the following in any component that is a child of Provider and access the score prop

function mapStateToProps(state) {
  return { score: state.score, status: state.status };
}

export default connect(mapStateToProps)(MyComponent)

However if this other component is a direct child of App component then you can also pass the score prop as a prop to this component from App like

<MyComponent score={this.props.score}/>
like image 79
Shubham Khatri Avatar answered Oct 11 '22 17:10

Shubham Khatri