How to access DVA Store in UMI application?

2.4k views Asked by At

Hi most of the react developers would find dvaJS and umiJS, heaven for state management and application development. Dva is elm based state management tool that use react-redux for state management.

Q: How to access DVA Store in UMI application, outside the component or without connect?

Q: How to dispatch DVA Store in UMI application, outside the component or without connect?

3

There are 3 answers

0
Charanjit Singh On BEST ANSWER

Q: How to access DVA Store in UMI application, outside the component or without connect?

A: https://v2.umijs.org/guide/with-dva.html#how-to-access-store-or-dispatch

It says use:

window.g_app._store

Q: How to dispatch DVA Store in UMI application, outside the component or without connect?

A: https://v2.umijs.org/guide/with-dva.html#how-to-access-store-or-dispatch

It says use:

window.g_app._store.dispatch('namespace/action')

Bonus:

Q: How to get state of DVA Store in UMI application, outside the component or without connect?

A: https://v2.umijs.org/guide/with-dva.html#how-to-access-store-or-dispatch

It says use:

window.g_app._store.getState()

Available Functions:

asyncReducers: {}
dispatch: ƒ ()
getState: ƒ f()
replaceReducer: ƒ (n)
runSaga: ƒ ()
subscribe: ƒ subscribe(listener)

Recommended: Instead of directly using it, write a Util that exports these functions.

0
gunpowderfans On

To access or dispatch DVA store in UMI app, you can use DVA hooks in functional components without connect. It can be only used with DVA v2.6.x.

In a functional component:

  • Access store:
const state = useSelector(state => state)
// If state in DVA store changed, rendered values in "state" can be changed in page too.

or

const store = useStore()
const state = store.getState()
// If state in DVA store changed, rendered values in "state" won't be changed in page.
  • Dispatch:
const dispatch = useDispatch()
dispatch({type: "namespace/action", payload: 12345})
0
tmarwen On

As and extra reference and for those searching for accessing the dva app reference outside of a react component context while using:

  • Umi.js v3+
  • Along with dva 2.6+ (as per the framework compatibility)

You can use the getDvaApp exported method:

import { getDvaApp } from 'umi';

const dispatch = getDvaApp()._store.dispatch;

// use the `dispatch`