I want to use dispatch() in class component
import React from "react";
import { connect } from "react-redux";
import { useDispatch } from "react-redux";
import {toDo} from "../patials/user";
class SignUp extends React.Component {
constructor(props) {
super(props);
this.onHandle = this.onHandle.bind(this);
}
onHandle() {
const dispatch = useDispatch();
dispatch(toDo());
}
render() {
return(
<button onClick={onHandle}>Action</button>
);
}
}
export default connect()(SignUp)
I got the error: React Hook "useDispatch" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
You cannot use useDispatch in a react class component, for the class component you need to map dispatch to props and use it like the following
// components/AddTodo.js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../redux/actions'
class AddTodo extends React.Component {
// ...
handleAddTodo = () => {
// dispatches actions to add todo
this.props.addTodo(this.state.input)
// sets state back to empty string
this.setState({ input: '' })
}
render() {
return (
<div>
<input
onChange={(e) => this.updateInput(e.target.value)}
value={this.state.input}
/>
<button className="add-todo" onClick={this.handleAddTodo}>
Add Todo
</button>
</div>
)
}
}
export default connect(null, { addTodo })(AddTodo)