In react-admin get access to redux store
Asked Answered
M

2

11

My question is related to react-admin repo.

I want to dispatch an action, outside of scope of a component, in order to do that, I've read that I need to get access to the actual redux store itself, and dispatch on in directly,

so I know that the Admin component has an initialState prop, but it only accepts default state object, not the store. So I can't make a store and pass it in.

My question is:

  • How do I access redux store of an Admin component?
  • How can I dispatch an action outside of a component, when using Admin as my main app component?

my current app entry looks like this:

<AppLayoutDirection>
    <Admin
      title="My App"
      locale="en"
      dataProvider={dataProvider}
      authProvider={authProvider}
      i18nProvider={i18nProvider}
      theme={themeProvider}
      customSagas={customSagas}
      appLayout={AppLayout}
    >
      {DynamicResource}
    </Admin>
  </AppLayoutDirection>
Maisonette answered 7/2, 2019 at 9:34 Comment(0)
S
2

When you say that you need to dispatch an action outside the scope of a component, I suppose that it's in reaction to another action that was dispatched in the past.

In that case, that's what react-admin calls a side effect. React-admin handles side effects using redux-saga. Here is how to create a custom saga:

// in src/bitcoinSaga.js
import { put, takeEvery } from 'redux-saga/effects';
import { showNotification } from 'react-admin';

export default function* bitcoinSaga() {
    yield takeEvery('BITCOIN_RATE_RECEIVED', function* () {
        yield put(showNotification('Bitcoin rate updated'));
    })
}

Register this saga in the <Admin> component as follows:

// in src/App.js
import React from 'react';
import { Admin } from 'react-admin';

import bitcoinSaga from './bitcoinSaga';

const App = () => (
    <Admin customSagas={[ bitcoinSaga ]} dataProvider={simpleRestProvider('http://path.to.my.api')}>
        ...
    </Admin>
);

export default App;

This is documented in the react-admin documentation, in the <Admin> chapter.

Spokeshave answered 7/2, 2019 at 13:27 Comment(0)
L
0

You could also simply use custom reducers if the computation is no async

    // in src/App.js

    import React from 'react';
    import { Admin } from 'react-admin';

    import reducers from './reducers';

    const App = () => (
        <Admin customReducers={customReducers} dataProvider={simpleRestProvider('http://path.to.my.api')}>
            ...
        </Admin>
    );

    export default App;

Lobscouse answered 18/6, 2020 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.