I need to access a property in the store before dispatching an action, in the container (code shown below) I am accessing using it using store.getState()
.
I would like to know if it is correct or a more appropriate way exists.
import { connect } from 'react-redux'
import LocationFinderSearch from './locationFinderSearch'
import { getLocations, setSearchValue } from './locationFinderSearchActions'
import store from '../app/store'
const mapStateToProps = (state, ownProps) => {
return {
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onLocationSearchClick: (e) => {
e.preventDefault()
let value = store.getState().locationFinderReducer.locationFinder.ui.inputValue
dispatch(getLocations(value))
},
onLocationInputChange: (e) => {
e.preventDefault()
let value = e.target.value
dispatch(setSearchValue(value))
}
}
}
const LocationFinderSearchContainer = connect(
mapStateToProps,
mapDispatchToProps
)(LocationFinderSearch)
export default LocationFinderSearchContainer
I think your first instinct should be to map the value from you state to a component prop like this:
const getInputValue = state =>
state.locationFinderReducer.locationFinder.ui.inputValue
const mapStateToProps = state => ({
inputValue: getInputValue(state),
})
Now that you have the inputValue in the components props, the question is how to use in your dispatch functions?
For this I would encourage you to put the immediate event handling (preventDefault and target.value) inside your component. This makes the mapDispatchToProps object much easier, puts the event handling encapsulated in your component and finally solves your problem of not using getState().
Your mapDispatchToProps becomes:
import { getLocations, setSearchValue } from './locationFinderSearchActions'
const mapDispatchToProps = {
getLocations,
setSearchValue,
}
The LocationFinderSearch component has to handle the events now and has access to the inputValue in this.props.inputValue:
class LocationFinderSearch extends React.Component {
...
onLocationSearchClick = (e) => {
const { getLocations, inputValue } = this.props
e.preventDefault()
getLocations(inputValue)
}
onLocationInputChange = (e) => {
const value = e.target.value
const { setSearchValue } = this.props
e.preventDefault()
setSearchValue(value)
}
...
}
I hope this answer will help you.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments