Skip to content

Commit

Permalink
Store Factory
Browse files Browse the repository at this point in the history
  • Loading branch information
BradDenver committed Nov 8, 2016
1 parent fdc5f93 commit 44ceb75
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
4 changes: 2 additions & 2 deletions app/components/PostList.js
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import React, { Component } from "react";

import { storeOrState } from "../stores";
import { postsStoreFor } from "../stores";
import render from "../tools/render";

@observer
Expand All @@ -18,7 +18,7 @@ export class PostList extends Component {

static propsFn(props, key, req) {
return {
store: storeOrState(req).posts
store: postsStoreFor(props.type, req)
};
}
};
Expand Down
35 changes: 29 additions & 6 deletions app/stores/index.js
@@ -1,21 +1,44 @@
import mobx, { autorun, createTransformer } from "mobx";
import sn from "selectn";
import _set from "lodash/set";

import hasDocument from "../tools/hasDocument";
import Posts from "./Posts";

export var storeOrState = (req) => {
export var storeOrState = (key, factory, req) => {
if (hasDocument || typeof req === "undefined") {
return stores;
// client: create store at key or return existing
let s = sn(key, stores);
if (!s) _set(stores, key, factory());

return sn(key, stores);
} else {
// server: get serialized state of store
// and add to req stores set

if (typeof req.SITEPOINT_state === "undefined") req.SITEPOINT_state = currentState;

return req.SITEPOINT_state;
return sn(key, req.SITEPOINT_state);
}
}

const stores = mobx.observable({
posts: new Posts()
});
export var postsStoreFor = (type = "Normal", req) => {
const key = `posts.${type}`;
const factory = () => new Posts(type);

return storeOrState(key, factory, req);
};

const stores = (hasDocument)
? mobx.observable({})
: mobx.observable({
posts: {
Normal: new Posts("Normal"),
Cats: new Posts("Cats"),
Dogs: new Posts("Dogs"),
Chickens: new Posts("Chickens")
}
});

let currentState;

Expand Down

0 comments on commit 44ceb75

Please sign in to comment.