yoshuawuyts / barracks

:mountain_railway: action dispatcher for unidirectional data flows
MIT License
177 stars 22 forks source link

Exception in reducer with namespace #53

Closed mantoni closed 8 years ago

mantoni commented 8 years ago

The following code throws:

const barracks = require("barracks");

const store = barracks();
store.model({
  namespace: 'ns',
  state: {},
  reducers: {
    a: () => {
      return { a: 1 };
    }
  }
});

const createSend = store.start();
const send = createSend('oups');

store.start();
send('ns:a', {}, () => {});

I get

.../barracks-test/node_modules/xtend/mutable.js:11
                target[key] = source[key]
                            ^

TypeError: Cannot set property 'a' of undefined
    at extend (.../barracks-test/node_modules/xtend/mutable.js:11:29)
    at null._onTimeout (.../barracks-test/node_modules/barracks/index.js:164:13)
    at Timer.listOnTimeout (timers.js:89:15)

When I don't use a namespace, this does not happen.

Apparently, namespaced modules are not initiallized by barracks. I can work around it like this:

store.model({
  namespace: 'ns',
  state: {
    ns: {}
  },
  // ...
});

This makes sense when looking at the implementation, however it's not very intuitive.

mantoni commented 8 years ago

Oh, I found it myself. Will send a PR.

mantoni commented 8 years ago

To clarify: It turns out adding the ns property in the code above works around the issue just because there is a property on the state object. It doesn't need to be named ns. Any property would do, as long as the initial state object is not empty.

yoshuawuyts commented 8 years ago

Ack