react-logo/frontend/src/reducers/messages.reducers.js

32 lines
822 B
JavaScript

import { ADD_MESSAGE, REMOVE_OLDEST_MESSAGE } from "../actions/message.actions";
const initialState = {
sortedByTimestamp: []
};
export function messagesReducer(state = initialState, action) {
switch(action.type) {
case ADD_MESSAGE:
return handleAddMessage(state, action);
case REMOVE_OLDEST_MESSAGE:
return handleRemoveOldestMessage(state, action);
};
return state;
}
function handleAddMessage(state, action) {
return {
...state,
sortedByTimestamp: [
{ ts: Date.now(), text: action.text, type: action.messageType },
...state.sortedByTimestamp
]
}
};
function handleRemoveOldestMessage(state, action) {
return {
...state,
sortedByTimestamp: state.sortedByTimestamp.slice(0, -1)
}
};