How do I access store state in React Redux?
You should create separate component, which will be listening to state changes and updating on every state change:
import store from '../reducers/store';
class Items extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
store.subscribe(() => {
// When state will be updated(in our case, when items will be fetched),
// we will update local component state and force component to rerender
// with new data.
this.setState({
items: store.getState().items;
});
});
}
render() {
return (
<div>
{this.state.items.map((item) => <p> {item.title} </p> )}
</div>
);
}
};
render(<Items />, document.getElementById('app'));
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
You need to use Store.getState()
to get current state of your Store.
For more information about getState()
watch this short video.
All of the answers are from pre-hook era. You should use useSelector-hook to get the state from redux.
In your redux-reducer file or somewhere where you can import it easily:
import { useSelector } from 'react-redux'
export function useEmployees() {
return useSelector((state) => state.employees)
}
In your application code:
const { employees } = useEmployees()
More information on redux-hooks: https://react-redux.js.org/api/hooks to accomplish this goal.