Hi,
I'm using redux with react-native and so far it's great!
In my app I have user profiles, and my state looks like:
{
users: {
"1": {id: "1", name: "Ran"},
"2": {id: "2", name: "Dan"}
}
}
Now I have a <Profile>
component that render a single user
class Profile extends React.Component {
componentDidMount() {
const { dispatch, userId } = this.props;
dispatch(loadUser(userId));
}
render() {
console.log(this.props.user.name);
}
}
When the component mounts I dispatch loadUser
action with the userId
passed as prop.
This makes a request to the API, and add the user response to my users
state.
Now, I want my Profile component to receive the user to render as prop.
So basically I want to do something like:
function mapStateToProps(state) {
return {
user: state.users[props.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
Obviously it can't work because I don't have access to props.
I can't use a state like selectedProfile
to filter because I'm rendering multiple profiles in my navigation stack, each one has different userId, if I use global selectedProfile state, it breaks the back button.
The only workaround I found is to create a ProfileContainer
component, that will filter the state by its prop and pass the single user to Profile
component.
class ProfileContainer extends React.Component {
render() {
let user = this.props.users[this.prop.userId];
return <Profile user={user} />
}
}
Does it make sense? Anybody else encounter this issue?
Thanks,
Ran.
Hey,
This is more a react-redux issue... I may be missing something, but it seems very simple to me, use "ownProps" argument that is passed to mapStateToProps, so your code above will look:
function mapStateToProps(state, ownProps) {
return {
user: state.users[ownProps.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
You definitely have access to the props of the component. How that looks ? See https://github.com/rackt/react-redux#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options for more details or https://github.com/rackt/redux/blob/master/examples/real-world/containers/UserPage.js for the real-world example...
I can't believe I missed that! Thanks @alanrubin
:thumbsup:
Please file such issues in react-redux in the future.
It's unrelated to this repository.
Most helpful comment
Hey,
This is more a react-redux issue... I may be missing something, but it seems very simple to me, use "ownProps" argument that is passed to mapStateToProps, so your code above will look:
You definitely have access to the props of the component. How that looks ? See https://github.com/rackt/react-redux#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options for more details or https://github.com/rackt/redux/blob/master/examples/real-world/containers/UserPage.js for the real-world example...