gaearon / flux-react-router-example

A sample app showcasing Flux with React Router
http://gaearon.github.io/flux-react-router-example/
MIT License
1.43k stars 174 forks source link

Example of a programmatic transition as a reaction to an event #13

Closed neverov closed 9 years ago

neverov commented 9 years ago

I would like to handle a situation when user creates an entity on a separate route and when operation is complete redirect him to the list of entities on a different route.

The flow is something like this:

  1. User clicks something like 'save stuff'
  2. An action is invoked and starts an async operation (ex. $.get('/stuff'))
  3. When operation finishes, store gets updated by dispatcher and emits a change event
  4. I need to make a transition via router with smth like router.transitionTo('whatever')

Maybe you can point me in the right direction how to handle this?

gaearon commented 9 years ago

Mostly it would follow the same flow:

  1. In component: StuffActionCreators.post(something)
  2. In action creator: StuffAPI.post(something)
  3. In stuff API: ajax('POST', '/stuff/post', something, StuffServerActionCreators.handlePost)
  4. In server action creator:
  handlePostStuff(err, response) {
    AppDispatcher.handleServerAction({
      type: err ? ActionTypes.POST_STUFF_ERROR : ActionTypes.POST_STUFF_SUCCESS,
      response: response,
      stuffId: err ? null : response.result
    });

    if (err) {
      console.error(err);
      // You might want to show error
      AlertActionCreators.showAlert(err.status ? AlertTypes.SERVER_ERROR : AlertTypes.CONNECTION_ERROR);
    } else {
      router.replaceWith('stuff', {
        stuffId: response.result
      });
    }
  }

Note that I'm assuming you're using Normalizr to flatten API responses, and thus POST /stuff is normalized into something like:

{
  result: 10, // stuff id
  entities: {
    stuffs: {
      10: {
        someStuffField: 'lala',
        otherStuffField: 42
      }
    }
    // if Stuff has any related nested entities, they will go here too
  }
}

This gives StuffStore the opportunity to consume posted stuff when POST_STUFF_SUCCESS is dispatched, similar to how content stores consume entities in this example.

Finallly, replaceWith (or transitionTo) is called on router instance. See flux howto in react-router.

neverov commented 9 years ago

Awesome!

Thanks a lot, that worked great!