What I want to have is a parameterized getter. Lets say I have module in redux users and every user has ID, I want by passing id return this user. My main issue is how do I pass id from component itself to mapStateToProps ?
Here is component:
const Main = (props) => {
console.log(props.userNameById(3)) // that's what I want pass an ID and get user
return <div>Hello</div>
}
// that's what I googled that inside props you should receive parameter, but how do I pass it ?
const mapStateToProps = (state, props) => {
console.log(props) // empty object
return {
userNameById: getName(state, props)
}
}
export default connect(mapStateToProps, null)(Main)
And then my rootReducer (I know it's not important for a question, but just in case):
import { combineReducers } from "redux";
import { createSelector } from "reselect";
import usersReducer, * as fromUsers from "./users/usersReducers";
import alertReducer from "./alerts/alertsReducers";
const rootReducer = combineReducers({
users: usersReducer,
alerts: alertReducer,
})
export const getName = (state, id) => return id; // let's just simplify a code, the main question how do I pass id
export default rootReducer;
mapStateToProps
is supposed to return a piece of state rather than a function that extracts the state.
if you wants to extract your state inside your component you could return users than at component find by some value:
const Main = (props) => {
console.log(props.users.find(user => user.id === 3))
console.log(getName(props.users, 3)) // or if you want to use some helper function directly
return <div>Hello</div>
}
const mapStateToProps = ({ users }) => ({ users })
export default connect(mapStateToProps, null)(Main)
but if you expect to receive id from props you could alternatively use id
props at your mapStateToProps:
const Main = (props) => {
console.log(props.user)
return <div>Hello</div>
}
const mapStateToProps = ({ users }, { id }) => ({ user: users.find(user => user.id === id) })
export default connect(mapStateToProps, null)(Main)