I have the following form:
let NoteForm = ({handleSave}) => {
return (
<form onSubmit={handleSave}>
<Field component="input" type="text" name="body" />
<button type="submit">Submit</button>
</form>
)
}
And:
const mapStateToProps = (state, ownProps) => {
return {
isNew: state.isNew
}
}
And finally:
const mapDispatchToProps = (dispatch, ownProps) => {
return {
handleSave: () => {
dispatch(saveNote(ownProps)) // ownProps does not contain "isNew" prop
}
}
}
The prop isNew
is not included in ownProps
. I hope it's an obvious mistake I am making here and unable to see it.
The component that renders NoteForm
is Note
and renders it conditionally as such:
{ (isNew || isEdit) && <NoteForm /> }
I can certainly pass the props in as attributes, but at this point I am stubborn as I am unable to understand why my prop is missing. I have already tried passing it in as an argument to my component as such: {handleSave, isNew}
but that doesn't work either.
For reference, my connect is:
NoteForm = connect(
mapStateToProps,
mapDispatchToProps
)(NoteForm);
The mapStateToProps(state, ownProps) is specified as the first argument of connect() call and its ownProps parameter receives the props object of the wrapper component. If the ownProps parameter is not present, React Redux skips calling the function at the props change.
mapStateToProps() is a function used to provide the store data to your component. On the other hand, mapDispatchToProps() is used to provide the action creators as props to your component.
useSelector and useDispatch are a set of hooks to use as alternatives to the existing connect() higher-order component. The equivalent of map state to props is useSelector. It takes in a function argument that returns the part of the state that you want. The equivalent of map dispatch to props is useDispatch.
The mapStateToProps and mapDispatchToProps deals with your Redux store's state and dispatch , respectively. state and dispatch will be supplied to your mapStateToProps or mapDispatchToProps functions as the first argument.
Currently I can't test this, but it makes sense that ownProps
are the properties that are passed to the component that is being returned by connect(...)(YourComponent)
. On the other hand isNew
is passed directly to YourComponent
by mapStateToProps
, so you wouldn't have access to it in the mapDispatchToProps
callback.
Somewhere in your app...
const ReturnedComponent = connect(...)(YourComponent)
render () {
<ReturnedComponent {...ownProps} />
}
These ownProps
are accessible by mapStateToProps
, but not the ones passed by mapDispatchToProps
.
See a possible solution to your problem here recommended by the creator of redux himself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With