Search code examples
reactjsreactjs-fluxfluxreact-router

react-router and flux - clearing state while transition


I am using react-router with the flux architecture (facebook's flux implementation).

Currently in my system I have route that says "chat/:topic".

When the user is entering this component, I am creating a subscription (using action creation, on componentWillMount) to a websocket server, and I am removing the subscription on componentWillUnmount.

When the user is moving to another route the whole workflow works alright - because react-router is unmounting my component.

When I transition inside my route (from "chat/games" to "chat/tv"), the component isn't mounted and I need to clear my state of the components.

I read about different actions that I can take and this on transition to dispatch an action "TRANSITION" and every relevant store will clear it's store.

In my opinion, this kind of action - is wrong, it couples my stores and my router.

How would you solve this problem? Is this an issue that I should raise to react-router and ask them to unmount inside my route?


Solution

  • I found the answer thanks to gaearon (https://github.com/gaearon/),

    Use a store to keep the selected topic and ask the messages store for messages, in flux you shouldn't remove anything from your store, unless you need it for a performance reasons.

    In my application, I must remove the messages (since they are large objects) and clear my subscriptions (to reduce the load on the server).

    In order to achieve this there were three solutions that I found:

    1. Use componentWillReceiveProps and check if the params are changed, if the params are changed - do whatever you need in order to clear the store - for example call ActionCreator and reset the state.
    2. Send a dispose payload in transition (inside Router.run) which will tell all the stores to clear themselves.
    3. last solution (which I used) making sure that my components are unmounted - Why? It is too error prone to clear the state on componentWillReceiveProps/dispose and it is clearer to just ensure the components are unmounted.

    Details on how to achieve this:

    https://github.com/rackt/react-router/issues/292

    https://github.com/rackt/react-router/issues/496#issuecomment-64152941