Hi everyone!
I’m completely new to React and currently trying to learn to use it with Redux.
Currentl for my first project I’m trying to build a shopping basket which includes items and each has a quantity (starting at 0) which I’d like to increase and decrease by clicking on the -/+ buttons.
So far I have done the following, but it’s just not working for me as I must be doing something very wrong and would really appreciate if someone could help me please!
Items Data:
export default () => {
return [
{
id: '1',
name: 'First Item',
price: 2.99,
ingredients: 'Lorem Ipsum',
image: 'img.jpg',
alt: 'item one',
quantity: 0
},
{
id: '2',
name: 'Second Item',
price: 3.99,
ingredients: 'Lorem Ipsum',
image: 'img.jpg',
alt: 'item two',
quantity: 0
}
];
};
Actions:
export const increaseQuantity = quantity => ({
type: 'INCREASE_QUANTITY',
quantity
});
export const decreaseQuantity = quantity => ({
type: 'DECREASE_QUANTITY',
quantity
});
Reducers:
export default (state = [], action) => {
switch (action.type) {
case 'INCREASE_QUANTITY':
console.log(action.quantity);
return {
...state,
quantity: action.quantity + 1
};
case 'DECREASE_QUANTITY':
if (state.quantity > 0) {
return {
...state,
quantity: action.quantity - 1
};
}
default:
return state;
}
};
Store:
import { createStore, combineReducers } from 'redux';
import items from './items';
import modifiers from '../reducers/modifiers';
export default () => {
const store = createStore(
combineReducers({
items,
modifiers
})
);
return store;
};
Item Component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { increaseQuantity, decreaseQuantity } from '../actions/items';
class Item extends Component {
render() {
return (
<div className="item">
<div className="item__image">
<img src={`/img/${this.props.image}`} alt={this.alt} />
</div>
<div className="item__info">
<h3>{this.props.name}</h3>
<h2>£{(this.props.price * this.props.quantity).toFixed(2)}</h2>
<p>Ingredients: {this.props.ingredients}</p>
<div className="quantity-modifier">
<button className="fast" onClick={() => {
dispatch(decreaseQuantity(this.props.quantity));
}}>-</button>
<span>{this.props.quantity}</span>
<button className="fast" onClick={() => {
dispatch(increaseQuantity(this.props.quantity));
}}>+</button>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.items
}
};
export default connect(mapStateToProps)(Item);
The items appear correctly in the resulting list, but when clicking on any of the -/+ buttons, I get:
ReferenceError: dispatch is not defined
Thank you very much for your attention in any case and I’d really appreciate if anyone could help me figure this thing out please.