I’m new to React and right now I’m working on a project where a user should be able to choose a base ingredient, and it gets added to an array. By clicking on another base ingredient the first one should be removed from the array. Right now the chosen ingredient only removes when clicking on the same one.
I want it to be removed when clicking on another one. Please help :)
import React from 'react';
import Actions from '../../../actions/actions';
import BaseIngredientButton from './BaseIngredientButton';
class BaseIngredientItem extends React.Component {
_OnClick (props) {
if (this.props.isChosen) {
Actions.removeItem(this.props.baseIngredient);
} else {
Actions.addItem(this.props.baseIngredient)
Actions.setBaseIngredient( this.props.baseIngredient );
}
console.log(this.props.isChosen)
}
render () {
return (
<BaseIngredientButton isChosen={this.props.isChosen} onClick={ this._OnClick.bind(this)} txt={ this.props.baseIngredient.name } />
)
}
}
BaseIngredientItem.propTypes = {
baseIngredient: React.PropTypes.object.isRequired,
isChosen: React.PropTypes.bool
}
export default BaseIngredientItem;
here is my store.js
let _cart = [];
const _removeItem = ( item ) => {
_cart.splice( _cart.findIndex( i => i === item ), 1 );
console.log("Ingredients in cart after removal", _cart);
};
const _getItemInCart = ( item ) => {
return _cart.find( ingredient => ingredient.name === item.name )
};
const _addItem = ( item ) => {
if (!_getItemInCart( item )) {
_cart.push(item);
}
console.log("Ingredients in cart after addition", _cart);
};
let _currentBaseIngredient = {};
const _setCurrentBaseIngredient = ( baseIngredient ) => {
_currentBaseIngredient = baseIngredient
};
here is my action.js
addItem( item ){
dispatch({
actionType: AppConstants.ADD_ITEM,
item
})
},
removeItem( item ){
dispatch({
actionType: AppConstants.REMOVE_ITEM,
item
})
},
setBaseIngredient( baseIngredient ){
dispatch({
actionType: AppConstants.SET_BASE_INGREDIENT,
baseIngredient
})
},
Actionsobject and the Store it communicates with?