Skip to content

Instantly share code, notes, and snippets.

@walaura
Last active September 26, 2017 11:21
Show Gist options
  • Save walaura/b72c1e5f95000b74df3069f145f4976b to your computer and use it in GitHub Desktop.
Save walaura/b72c1e5f95000b74df3069f145f4976b to your computer and use it in GitHub Desktop.
Extremely lazy & ugly React stores
import {add as messageAdd} from './messageStore';
import React, { Component } from 'react';
class Messager extends Component {
constructor(props) {
super(props);
messageAdd('hi');
}
}
export const INITIAL_STATE = [];
let messages = INITIAL_STATE;
let subscriptions = [];
/*
any receiver component can read the store by
subscribing to its changes
*/
export const subscribe = callback => {
subscriptions.push(callback);
notify() /*and this instantly feeds the current state to prevent race conditions*/
};
/*
you can only edit the store within the store itself,
this example function adds a message and pops it out
(technically whatever the last one is) after 4 seconds
i use this pattern a lot, with extra options, for
feedback/error toasts
*/
export const add = message => {
messages.push({
text: message
});
/*and must notify() of any changes*/
notify();
setTimeout(()=>{
messages.pop();
notify();
},4000);
};
/*
call this whenever the store changes to
notify components
*/
const notify = () => {
subscriptions.map(notify => notify([...messages]));
/*
im cloning the state so receivers cant mess with it
but this is v fancy, please dont use this code at all
in any serious/team projects just use redux
*/
};
import {subscribe as messageSubscribe, INITIAL_STATE as messageInitialState} from './messageStore';
class Receiver extends Component {
constructor(props) {
super(props);
this.state = {
messages: messageInitialState,
};
messageSubscribe(messages => {
this.setState({
'messages': messages,
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment