Reputation: 417
In my code below, I have a delete button that should be deleting the data if clicked. However, when I click on it, I am seeing through console.log that it is returning undefined instead of the id number. Can't seem to figure out why. Any help will be greatly appreciated. Thank you.
//Actions File
export const GET_ITEMS = 'GET ITEMS';
export const FETCH_ITEMS_SUCCESS = 'FETCH ITEMS SUCCESS';
export const FETCH_ITEMS_ERROR = 'FETCH ITEMS ERROR';
export const DELETE_ITEM = 'DELETE_ITEM';
export const getItems = () => ({
type: GET_ITEMS
});
export const deleteItem = (itemId) => ({
type : DELETE_ITEM,
payload: itemId
});
//App.js
class App extends Component {
componentDidMount() {
this.props.getItems()
}
static propTypes = {
getItems: PropTypes.func.isRequired,
deleteItem: PropTypes.func.isRequired
}
handleDelete = (id) =>{
this.props.deleteItem(id)
console.log(this.props.deleteItem(id));
}
render() {
const { itemsList} = this.props.items
return (
<div className="container app-wrapper">
<header>
{itemsList.map(item => (<h1 key={item.id}>{item.title} <button onClick={this.handleDelete.bind(this, item.id)}>delete</button></h1>))}
</header>
</div>
);
}
}
const mapStateToProps = state => ({
items: state.items
});
export default connect(mapStateToProps, {getItems, deleteItem})(App);
Upvotes: 1
Views: 485
Reputation:
You are referencing your delete action incorrectly in connect. deleteItem expects an id param passed into it.
Try this,
const mapStateToProps = state => ({
items: state.items
});
const mapDispatchToProps = (dispatch) =>
{
return {
deleteItem: (id) => dispatch(actions.deleteItem(id)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
Upvotes: 0
Reputation: 14365
The dispatched action should return undefined
, because it does not return anything. You are misunderstanding how data flows in the Redux/reducer pattern.
Here's the basic flow of a Redux update:
connect
sees that the Redux state has changed, and triggers a re-render of the children components.mapStateToProps
).You cannot call an action and receive the updated state as the return value. It breaks the fundamental pattern of how data flows/updates in Redux.
Upvotes: 2