goatslacker / alt

Isomorphic flux implementation
http://alt.js.org/
3.45k stars 322 forks source link

Derived/Calculated State - storing functions in state doesn't work with Alt instances? #674

Closed jayalfredprufrock closed 8 years ago

jayalfredprufrock commented 8 years ago

I'm in the process of updating an app built on Alt to be isomorphic / universal. I'm using the instance based approach, and bootstrap to hydrate the client. Everything was going smoothly until I realized that helper functions stored in my store's state are no longer available when I use this.alt.getStore('AppStore') My guess is this has something to do with the serialization/unserialization process? Or perhaps differences in addStore() versus createStore? Or maybe a bug?

Either way I'm a bit stuck. It was super convenient to dynamically compute certain things from the state and having those functions live in the state class kept everything related in one place. I realize I could create helpers that i pass the state to that would perform these calculations, but I'm hoping there is a better way.

Redux has a library called Reselect that looks really useful, but I don't think that would solve the problem in this case, since using it would still require storing a function in state, which doesn't seem possible using the instance based approach.

Anybody have thoughts on any of this?

goatslacker commented 8 years ago

Can you extract those helper functions into standalone functions? You can then call those functions yourself and pass the store's state in.

eg:

function getUserById(users, id) {
  return users.find(user => user.id === id)
}

getUsersById(UsersStore.getState(), 2)
jayalfredprufrock commented 8 years ago

Absolutely, and this is ultimately what I'll have to do. Just a bummer because it's quite a bit more verbose to invoke than what I had before.

Thinking out loud here...it should be possible to wrap the store with the helpers after it has been processed by Alt somehow, right?

goatslacker commented 8 years ago

The helpers shouldn't exist in state though. State should be serializable if you want to do universal rendering.

I think if you export them as public methods of the store then it should be fine.

jayalfredprufrock commented 8 years ago

Sorry, that's actually what I meant. Public methods of my stores that used to be accessible before I started doing universal rendering are now no longer available.

goatslacker commented 8 years ago

Do you have a failing test case by any chance?

jayalfredprufrock commented 8 years ago

I started to put together a test case from one of your existing ones and what I thought would fail didn't. Soooooo, forgive the noise, this must be an issue on my end.