0

I have custom react-admin pages that often query multiple resources (account, posts, comments for the same page).

I am using redux sagas to handle API requests as side-effects while decoupling my view component from this logic.

Since react-admin 3.0, to correctly use the dataProvider with all react-admin's error handling and notifications, I should use the useDataProvider hook, but - hooks cannot be used from within sagas, so how should I orchestrate multiple requests from a saga?

Or is there another practice, while keeping the requirements I mentioned?

Thanks!

ilaif
  • 348
  • 2
  • 13

1 Answers1

1

React-admin 3.0 de-emphasizes sagas, and you can simply chain data provider calls using the Promise returned the useDataProvier hook, as explained in the react-admin documentation (https://marmelab.com/react-admin/Actions.html):

import React from 'react';
import { useDataProvider, useNotify, useRedirect, Button } from 'react-admin';

const ApproveButton = ({ record }) => {
    const notify = useNotify();
    const redirect = useRedirect();
    const dataProvider = useDataProvider();
    const approve = () => dataProvider
        .update('comments', { id: record.id, data: { isApproved: true } })
        .then(response => {
            // call the data provider again here
            data.provider.getMany('...')
        })
        .catch(error => {
            // failure side effects go here 
            notify(`Comment approval error: ${error.message}`, 'warning');
        });

    return <Button label="Approve" onClick={approve} />;
};

The react-admin demo example shows how to fetch several resources to populate a complex page (the dashboard), and it should be a good inspiration for your use case:

https://github.com/marmelab/react-admin/blob/master/examples/demo/src/dashboard/Dashboard.tsx

MaxAlex
  • 2,919
  • 1
  • 14
  • 14
François Zaninotto
  • 7,068
  • 2
  • 35
  • 56
  • Thanks! The thing is that in the linked example, the view and the business logic are merged. It misses the nice separation of concerns that redux connect is giving us along with the Sagas. I guess I can always create a hook and use it in my component, but still, the component is aware of the hook, making it aware of the business logic - How wonder how we can achieve "view only components" with hooks. Maybe it's a more general question. wdyt? – ilaif May 11 '20 at 21:40
  • Moving your business logic to a hook is the 'react way'. And I see no problem in letting the 'view component' know which hook he should use.If you're worried about testing the view only, you can always mock the hook (e.g. using jest). Or you can create 2 components: one with the "pure view", and another with the hook. However, this makes the React tree deeper and harder to debugs. But react-admin uses this approach for some of its components (e.g. `List` executes `useListController` and passes the results to `ListView`, which is "pure vue"). – François Zaninotto May 13 '20 at 05:47