Reputation: 147
I am having problems with redux. I'm trying to dispatch a value from a search bar I created that will get the client ID of who I type in. The auto-suggestion works fine. The Item (ID Number) and value (Client name) correctly in the console log. but I am unable to dispatch it to the reducer. I keep getting a "dispatch" is not a function error. Redux is imported. Any Ideas?
class ClientSearch extends Component {
constructor(props){
super(props)
this.state = {
}
lowerCase = (str) => {
console.log(str);
return str;
}
test = (value, item) => {
console.log('Inside Test',item.numClientID);
let { dispatch } = this.props
dispatch(fetchClient(item.numClientID))
}
}
render() {
let value = '';
return (
<div>
<ReactAutocomplete
items={this.props.clients}
shouldItemRender={(item, value) => item.txtName.toLowerCase().indexOf(value.toLowerCase()) > -1}
getItemValue={(item) => item.txtName}
renderItem={(item, highlighted) =>
<div
key={item.numClientID}
style={{ backgroundColor: highlighted ? 'purple' : 'transparent'}}
>
{item.txtName}
</div>
}
value={this.state.selectedClient}
onChange={e => this.setState({ selectedClient: e.target.value })}
onSelect={(value, item) => this.test(value,item)}
/>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log('map state', state)
return {
clients: state.client.clients
};
};
export default connect(mapStateToProps, dispatch =>
bindActionCreators(listClients, dispatch, fetchClient, dispatch)
)(ClientSearch);
Upvotes: 0
Views: 103
Reputation: 3687
const mapStateToProps = (state) => {
console.log('map state', state)
return {
clients: state.client.clients
};
};
export default connect(mapStateToProps, dispatch=>bindActionCreators({listClients, fetchClient},dispatch))(ClientSearch);
This should work for you
Upvotes: 1
Reputation: 13986
Try doing it like this.
const mapStateToProps = (state, ownProps) => ({
clients: state.client.clients
});
const mapDispatchToProps = (dispatch) => ({
fooAction: (payload) => dispatch(foo(payload)),
barAction: () => dispatch(bar()),
});
export default connect(mapStateToProps, mapDispatchToProps)(ClientSearch);
Here foo()
and bar()
are actions that get dispatched so for example the method foo()
can be defined and declared like this.
function foo(payload) {
return dispatch => SOME_API_METHOD(payload)
.then(response => {
dispatch({
type: 'SOME_COOL_ACTION_NAME',
info: response
});
})
}
For reference have a look at react-redux Along with redux-thunk
Upvotes: 2