Skip to content

Instantly share code, notes, and snippets.

View JamesTheHacker's full-sized avatar

0xDEADBEEF JamesTheHacker

  • United Kingdom
View GitHub Profile
constructor(reducer, initialState = {}) {
this.store = [ initialState ];
this.reducer = reducer;
this.subscribers = [];
}
// This is a reducer, same as Redux's
const reducer = (state, action) => {
switch(action.type) {
case 'FETCHING_TWEETS':
return {...state, fetchingTweets: true};
break;
case 'TWEETS_RECEIVED':
return { ...state,
fetchingTweets: false,
tweets: action.tweets
// Returns the last element from the state store
getState() {
return this.store[this.store.length - 1];
}
// Subscribe to receive notifications
store.subscribe(action => {
// Check the type of action
if(action == ‘TWEETS_RECEIVED’) {
// Clear notification
document.getElementById(‘notification’).innerText = ‘’;
// Construct the HTML for the tweets list
// This is a reducer, same as Redux's
const reducer = (state, action) => {
switch(action.type) {
case 'FETCHING_TWEETS':
return {...state, fetchingTweets: true};
break;
case 'TWEETS_RECEIVED':
return { ...state,
fetchingTweets: false,
tweets: action.tweets
store.dispatch({
type: ‘TWEETS_RECEIVED’,
isFetching: false,
tweets: [
{
username: ‘JamesJefferyUK’,
message: ‘💜 I ❤ Redux!’
},
{
username: ‘JamesJefferyUK’,
const initialState = {
fetchingTweets: false,
tweets: []
};
const store = new FauxRedux(reducer, initialState);
/*
* This class is a high level view of how Redux works under the hood.
* This example includes no error handling or immutability and is used
* purely as an example to demonstrate how Redux works.
*/
class FauxRedux {
// Just like Redux we accept a reducer, and some initial state
constructor(reducer, initialState = {}) {
this.store = [ initialState ];
// Shallow freeze
Object.freeze(state);
// This will not work
state.twitter = '@zuck';
// Look, it's still @JamesJefferyUK
console.log(state.twitter);
// But this works because we're modifying a reference value (an object)
const deepFreeze = o => Object
.getOwnPropertyNames(o)
.forEach(n=> {
if (typeof o[n] == 'object' && o[n] !== null)
deepFreeze(o[n]);
return Object.freeze(o);
});