ui-router / redux

UI-Router plugin for Redux integration
MIT License
12 stars 6 forks source link

How to properly use resolvers #4

Open mczp opened 6 years ago

mczp commented 6 years ago

Coming from the old angular I loved the resolvers in ui-router, however I'm having trouble using them with Redux. My main issue is that usually I enclose my API into a service which was then injected into the router, however with redux, I have no idea how to achieve this... A little example/demo would be very helpful

mczp commented 6 years ago

After tinkering I figured a way to access the API from the injected transition, however I would still be interested about how to reconcile redux with the resolvers via action creators and reducers

ghost commented 6 years ago

Don't know if this is the recommended way however I found that dependency injection is a bad idea, on the other side resolvers can be easily reconciled with the redux store, below is an example of a simple config I'm using:

import FabricsList from './components/fabric_list'

import { api } from 'api/wsrpc'
import { store } from 'app/store'
import { BROCADE_GET_FABRICS } from './actions/types'

// Configuration for routes [states]
export const states = [{
  name: 'app.fabrics',
  url: '/fabrics',
  resolve: [
    {
      token: 'fabrics',
      resolveFn: function () {
        // An API method which returns a promise
        let p = api.sendRequest(BROCADE_GET_FABRICS)
        // Register the callback to update redux store when promise gets resolved
        p.then((data)=> {
          store.dispatch({type: BROCADE_GET_FABRICS, data})
        })
        return p
      }
    }
  ],
  component: FabricsList,
}]
elbaro commented 6 years ago

Is there any other way to access dispatch() and avoid import store singleton?

ghost commented 6 years ago

Technically yes, you can inject it into the router and use dependency injection to resolve it in the router resolve function. There might be another way perhaps by using redux bindActionCreators however on the doc page it says:

Normally you should just call dispatch directly on your Store instance. 
If you use Redux with React, react-redux will provide you with the dispatch 
function so you can call it directly, too.

So apparently it is normal to pass the singleton around...