Welcome to **PART 4 **of building a simple shopping cart that takes advantage of React DnD. In PART 3, we integrated React DnD into our React App. if you will like to start building from PART4, make sure to clone and download PART3’s code from this branch as PART 4 is a continuation.
In this article, we shall continue building our shopping cart by using React Actions and Reducers to move items from the drag source to the drop target in response to the React DnD endDrag
event. At the end of this article, we shall learn
_All code for this section is found in the branch _here
As of now, whenever we drag an item from the drag source to the drop target, nothing special happens order than some console log messages.
Fig2 The current state of our React App
What we are trying to build now is to enable the items dropped into the drop target to actually move into it as shown in Fig1 above.
The way we integrated our React DnD, whenever we drop a compatible item into the drop target, the endDrag
event is triggered. We want to respond to this event by informing the store on which action to take.
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using
[_store.dispatch()_](https://redux.js.org/api/store#dispatchaction)
.
Move to src/actions/phones.js
and modify it as below
export const RECEIVE_PHONES = 'RECEIVE_PHONES'
export const MOVE_INCART = 'MOVE_INCART'
export function receivePhones(phones){
return{
type: RECEIVE_PHONES,
phones
}
}
export function moveIncart(phone_id){
return{
type: MOVE_INCART,
id: phone_id
}
}
Our action is a plain JavaScript object with a compulsory type
property which typically takes a string constant value that indicates the type of action being performed. In this case, MOVE_INCART.
All we need next is the item’s id we want to move phone_id
which is passed to the moveIncart()
function as an argument.
After the action has been sent to the store, We need a reducer to specify how the state will change in response to the action.
Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.
#drag-and-drop #reactjs #redux #shopping-cart