I tried to call an action from my component. But, When I run the call the below action from my component I got a type error that tells that dispatch is not a function. how to get rid of this error.
action:
import { FETCH_ALL, FETCH_CUSTOMER, CREATE_CUSTOMER, DELETE_ALL, DELETE_CUSTOMER, UPDATE_CUSTOMER } from '../actionTypes';
import * as api from '../api/index';
export const getCustomers = () => async (dispatch) => {
try {
const { data } = await api.getCustomers();
console.log(dispatch);
dispatch({ type: FETCH_ALL, payload: data});
} catch(err) {
console.log(err);
}
};
component:
function Home() {
const customers = useSelector((state) => state.customers);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getCustomers);
},[dispatch]);
return (
<div style={{paddingLeft: '50px', paddingRight: '50px'}}>
<header>
<h1 style={{textAlign: 'center', color: 'green'}}>Customer Relationship Management</h1>
</header>
<button onClick={dispatch(getCustomers)}>Fetch Customers</button>
<div className="heading">
<h3>Customer Details: </h3>
<button className="homePageButtons"><Link className="homePageLinks" to="/add-customer">Add Customer</Link></button>
</div>
<div className="customerTable">
<table>
<thead>
<tr>
<th>ID</th>
<th className="name">First Name</th>
<th className="name">Last Name</th>
<th className="email">Email</th>
</tr>
</thead>
<tbody>
{customers.map((customer) => (
<tr>
<td>customer.id</td>
<td>customer.firstName</td>
<td>customer.lastName</td>
<td>customer.email</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
The below error occurs:
customer.js:11 TypeError: dispatch is not a function
at customer.js:9
I log the dispatch, it is showing the below object...
SyntheticBaseEvent {_reactName: "onClick", _targetInst: null, type: "click", nativeEvent: MouseEvent, target: button, …}
I applied the middleware in the index.js file ad below...
const store = createStore(reducers, compose(applyMiddleware(thunk)));