Search code examples
javascriptreactjsreactjs-fluxflux

Whose job is it in Flux/React to set the page title?


Let's say I start with the Facebook flux-chat example. There are multiple threads each with messages. I want to write code so that when I click to navigate to a different thread, I change the page title accordingly.

Who sets the page title?

  • The click handler in the threads list component (unlikely)
  • The action creator that gets called by the component
  • A new store that I create that listens to navigation-related actions
  • A new react component that doesn't actually have a DOM presence (the page title is kind of like a custom view component, right?)

Now let's say I want to go a step further and implement a blinking page title like Facebook when the user gets a new message. When a new message comes in, it comes through some web socket or AJAX response handler.

Now who sets the page title?

  • This new message handler
  • The action creator that gets called by the handler
  • Some new store (see above)
  • Some react component (see above)

But when I set the title this time, I need to know how many unread messages there are. I don't know this until the action has fired and all the stores have updated data, so it seems the first two options are out.

Edit:

After posting, I discovered this gist that appears to register for a callback on the dispatcher, but isn't a store. Is this the right approach? What would you call this thing, if not a store?


Solution

  • The title is a part of your application state, so you need a store to keep it, say TitleStore. When it changes you need to apply change to the window:

     TitleStore.on('change', function() {
       document.title = TitleStore.getTitle();
     });
    

    Or you can implement this as a React component instead. It would apply the change on mount (or use this module: https://github.com/gaearon/react-document-title).

    One thing left: actions that change the store. You might be tempted to create a special action, like SET_TITLE, but it's absolutely wrong. Actions should be something that user does, no something that you want to happen. Instead you should use existing actions, like LINK_CLICKED or THREAD_SELECTED, etc. Other stores would react to this actions accordingly and you could use them to update title with the help of waitFor.