Reputation: 458
I am new to React/Redux binding and I`m gonna implement Redux component with form that refresh jokes with possibility of changing quantity of fetched jokes (1 joke by default):
import fetchJokes from '../actions/jokes';
import { connect } from 'react-redux';
class FormToRefresh extends React.Component {
constructor(props) {
super(props);
this.state = {value: 1};
this.handleInput = this.handleInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInput(e) {
let input = e.target.value;
if(isNaN(input)||input > 10||input< 1) {
alert("Wrong input");
this.setState({value: 1});
} else {
this.setState({value: input})
}
handleSubmit(e) {
// this should trigger dispatching fetchJokes action
// but how to integrate dispatch() function here...
dispatch(fetchJokes(this.state.value));
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit>
<label>Enter amount of jokes (from 1 to 10):
<input type="text" value={this.state.value} onInput={this.handleInput} />
</label>
<button type="submit">Refresh</button>
</form>
</div>)
}
}
export default connect()(FormToRefresh);
Generally, I look up into guide https://redux.js.org/basics/usage-with-react#implementing-other-components , I tend to implement class-based component rather than function-based. I have some misunderstanding of how dispatch() method was integrated into guide`s AddTodo function and how should I implement it in my FormToRefresh class? If you notice any other mistake, please, let me know.
Upvotes: 3
Views: 23172
Reputation: 282110
When you don't pass mapDispatchToProps
, the connect function makes dispatch
available as prop to the component and hence you can make use of that
// bind the below function
handleSubmit = (e) => {
const { dispatch } = this.props;
dispatch(fetchJokes(this.state.value));
}
or
pass the action to connect like
// bind the below function
handleSubmit = (e) => {
const { fetchJokes } = this.props;
fetchJokes(this.state.value);
}
export default connect(null, { fetchJokes })(FormToRefresh);
Upvotes: 9