Skip to content

Instantly share code, notes, and snippets.

@parwatcodes
Created May 24, 2017 09:48
Show Gist options
  • Save parwatcodes/d4d0713426ba34d9e7df68744d82c51a to your computer and use it in GitHub Desktop.
Save parwatcodes/d4d0713426ba34d9e7df68744d82c51a to your computer and use it in GitHub Desktop.
import { createStore, combineReducers } from 'redux';
export const ONLINE = `ONLINE`;
export const AWAY = `AWAY`;
export const BUSY = `BUSY`;
export const OFFLINE = `OFFLINE`;
export const UPDATE_STATUS = `UPDATE_STATUS`;
export const CREATE_NEW_MESSAGE = `CREATE_NEW_MESSAGE`;
// inital state
const defaultState = {
messages: [{
date: new Date('2016-10-10'),
postedBy: 'parwat',
content: 'redux start test app'
}, {
date: new Date('2016-10-10'),
postedBy: 'ramesh',
content: 'nodejs start app'
}],
userStatus: ONLINE
}
// user reducer - 1
const userStatusReducer = (state = defaultState.userStatus, {type, value}) => {
switch(type) {
case UPDATE_STATUS:
return value;
}
return state;
}
// message reducer - 2
const messagesReducer = (state = defaultState.messages, { type, value, postedBy, date }) => {
switch(type) {
case CREATE_NEW_MESSAGE:
const newState = [{date, postedBy, content:value }, ...state];
return newState;
}
return state;
}
// combining All reducers (user and message)
const combinedReducers = combineReducers({
userStatus: userStatusReducer,
messages: messagesReducer
})
// creating store from reducers
const store = createStore(combinedReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
document.forms.newMessage.addEventListener("submit", (e) => {
e.preventDefault();
const value = e.target.newMessage.value;
const username = localStorage[`preferences`] ? JSON.parse(localStorage[`preferences`]).userName : "Jim";
store.dispatch(newMessageAction(value, username))
})
const render = () => {
const { messages, userStatus } = store.getState();
document.getElementById('messages').innerHTML = messages.sort((a, b) => b.date - a.date)
.map(message => (`
<div>
${message.postedBy}: ${message.content}
</div>
`)).join("");
document.forms.newMessage.fields.disabled = (userStatus === OFFLINE);
document.forms.newMessage.newMessage.value = "";
}
// status action 1
const statusUpdateAction = (value) => {
return {
type: UPDATE_STATUS,
value
}
}
// newmessage action 2
const newMessageAction = (content, postedBy) => {
const date = new Date();
return {
type: CREATE_NEW_MESSAGE,
value: content,
postedBy,
date
}
}
document.forms.selectStatus.addEventListener("change", (e) => {
store.dispatch(statusUpdateAction(e.target.value));
})
render();
store.subscribe(render);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment