The reducer function
We start with the action type INITIAL_LOAD
:
export default function cards(state = [], action) { switch (action.type) { case INITIAL_LOAD: return action.data;
Here, we return the new data; notice we do not mutate our state. The second one is the ADD_CARD
action:
case ADD_CARD: if (state.filter(card => card._id === action.id).length > 0) { return state; } return [ ...state, { _id: action.id, title: action.title, task: action.task, status: action.status } ]
In our app, when we create a new card, we dispatch the ADD_CARD
action, and at the same time, we listen for collection changes. Since we are changing the collection (adding a new card), we will dispatch the RECEIVE_CARD
action. To prevent adding one item twice, we return the original state if the card is already added. We can add a filter condition in both actions; this way, we won't have to worry about race conditions, especially since the data on the client MongoDB...