I´m trying to build my first connection between a React component to Redux to gather data from my node API.
This is a simple component for now, but it will grow in the future and will derive subcomponents that will allow me to build a full User CRUD interface (list, edit, delete, view, etc.). In that sense, I need to connect the action functions to the object this.props so that it can be inheritated by the child components.
Here is my code:
Component UserGrid - A table data grid that will load users information
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as userActions from '../../actions/userActions';
class UserGrid extends React.Component {
componentWillMount() {
this.props.fetchUsers();
}
render() {
const mappedUsers = users.map(user => <li>{user.email}</li>);
return (
<div>
<ul>{mappedUsers}</ul>
</div>
);
}
}
function mapStateToProps(state) {
return {
users: state.users
}
}
export default connect(
mapStateToProps,
bindActionCreators(userActions, dispatch)
)(UserGrid);
My userAction, that effectively will load users from an AJAX call:
import axios from "axios";
export function fetchUsers() {
return function(dispatch) {
axios.get("/api/users")
.then((response) => {
dispatch({type: "FETCH_USERS_FULFILLED", payload: response.data});
})
.catch((err) => {
dispatch({type: "FETCH_USERS_REJECTED", payload: err});
})
}
}
With this code I´m getting the following error:
Uncaught ReferenceError: dispatch is not defined
at Object.<anonymous> (bundle.js:37984)
at __webpack_require__ (bundle.js:556)
at fn (bundle.js:87)
at Object.<anonymous> (bundle.js:37711)
at __webpack_require__ (bundle.js:556)
at fn (bundle.js:87)
at Object.<anonymous> (bundle.js:8466)
at __webpack_require__ (bundle.js:556)
at fn (bundle.js:87)
at Object.<anonymous> (bundle.js:588)
(anonymous) @ bundle.js:37984
__webpack_require__ @ bundle.js:556
fn @ bundle.js:87
(anonymous) @ bundle.js:37711
__webpack_require__ @ bundle.js:556
fn @ bundle.js:87
(anonymous) @ bundle.js:8466
__webpack_require__ @ bundle.js:556
fn @ bundle.js:87
(anonymous) @ bundle.js:588
__webpack_require__ @ bundle.js:556
(anonymous) @ bundle.js:579
(anonymous) @ bundle.js:582
What is the correct way to connect my component to the Redux services created?
dispatchas an argument tobindActionCreatorsbut it isn't defined anywhere.