Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] add useOptimisticQuery hook #3248

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 5 additions & 20 deletions packages/ra-core/src/actions/dataActions/crudGetOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,14 @@ import {
export const crudGetOne = (
resource: string,
id: Identifier,
basePath: string,
refresh: RefreshSideEffect = true
meta: any
): CrudGetOneAction => ({
type: CRUD_GET_ONE,
payload: { id },
meta: {
resource,
fetch: GET_ONE,
basePath,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decoupling side effects, refs #2952

onFailure: {
notification: {
body: 'ra.notification.item_doesnt_exist',
level: 'warning',
},
redirectTo: 'list',
refresh,
},
...meta,
},
});

Expand All @@ -41,12 +32,7 @@ export interface CrudGetOneAction {
readonly meta: {
resource: string;
fetch: typeof GET_ONE;
basePath: string;
onFailure: {
notification: NotificationSideEffect;
redirectTo: RedirectionSideEffect;
refresh: RefreshSideEffect;
};
[key: string]: any;
};
}

Expand All @@ -68,11 +54,9 @@ export interface CrudGetOneFailureAction {
readonly requestPayload: RequestPayload;
readonly meta: {
resource: string;
notification: NotificationSideEffect;
redirectTo: RedirectionSideEffect;
refresh: RefreshSideEffect;
fetchResponse: typeof GET_ONE;
fetchStatus: typeof FETCH_ERROR;
[key: string]: any;
};
}

Expand All @@ -87,5 +71,6 @@ export interface CrudGetOneSuccessAction {
resource: string;
fetchResponse: typeof GET_ONE;
fetchStatus: typeof FETCH_END;
[key: string]: any;
};
}
34 changes: 21 additions & 13 deletions packages/ra-core/src/controller/EditController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { ReactNode, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { reset as resetForm } from 'redux-form';
import inflection from 'inflection';
import { crudGetOne, crudUpdate, startUndoable } from '../actions';

import { crudUpdate, startUndoable } from '../actions';
import { REDUX_FORM_NAME } from '../form';
import { useCheckMinimumRequiredProps } from './checkMinimumRequiredProps';
import { Translate, Record, Identifier, ReduxState } from '../types';
import { RedirectionSideEffect } from '../sideEffect';
import { useTranslate } from '../i18n';
import useGetOne from './useGetOne';

interface ChildrenFuncParams {
isLoading: boolean;
Expand Down Expand Up @@ -85,23 +87,29 @@ const EditController = (props: Props) => {

const { basePath, children, id, resource, undoable } = props;

const record = useSelector((state: ReduxState) =>
state.admin.resources[props.resource]
? state.admin.resources[props.resource].data[props.id]
: null
);

const isLoading = useSelector(
(state: ReduxState) => state.admin.loading > 0
);

const version = useSelector(
(state: ReduxState) => state.admin.ui.viewVersion
);

const { data: record, loading } = useGetOne(
resource,
id,
{
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now it's the controller who decides the side effects, not the action creator

basePath,
onFailure: {
notification: {
body: 'ra.notification.item_doesnt_exist',
level: 'warning',
},
redirectTo: 'list',
refresh: true,
},
},
version
);

useEffect(() => {
dispatch(resetForm(REDUX_FORM_NAME));
dispatch(crudGetOne(resource, id, basePath));
}, [resource, id, basePath, version]);

if (!children) {
Expand Down Expand Up @@ -139,7 +147,7 @@ const EditController = (props: Props) => {
);

return children({
isLoading,
isLoading: loading,
defaultTitle,
save,
resource,
Expand Down
39 changes: 21 additions & 18 deletions packages/ra-core/src/controller/ShowController.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { ReactNode, useEffect } from 'react';
import { ReactNode } from 'react';
// @ts-ignore
import { useDispatch, useSelector } from 'react-redux';
import { useSelector } from 'react-redux';
import inflection from 'inflection';
import { crudGetOne } from '../actions';

import { useCheckMinimumRequiredProps } from './checkMinimumRequiredProps';
import { Translate, Record, Identifier, ReduxState } from '../types';
import { useTranslate } from '../i18n';
import useGetOne from './useGetOne';

interface ChildrenFuncParams {
isLoading: boolean;
Expand Down Expand Up @@ -75,25 +76,27 @@ const ShowController = (props: Props) => {
useCheckMinimumRequiredProps('Show', ['basePath', 'resource'], props);
const { basePath, children, id, resource } = props;
const translate = useTranslate();
const dispatch = useDispatch();

const record = useSelector((state: ReduxState) =>
state.admin.resources[props.resource]
? state.admin.resources[props.resource].data[props.id]
: null
);

const isLoading = useSelector(
(state: ReduxState) => state.admin.loading > 0
);

const version = useSelector(
(state: ReduxState) => state.admin.ui.viewVersion
);

useEffect(() => {
dispatch(crudGetOne(resource, id, basePath));
}, [resource, id, basePath, version]);
const { data: record, loading } = useGetOne(
resource,
id,
{
basePath,
onFailure: {
notification: {
body: 'ra.notification.item_doesnt_exist',
level: 'warning',
},
redirectTo: 'list',
refresh: true,
},
},
version
);

if (!children) {
return null;
Expand All @@ -109,7 +112,7 @@ const ShowController = (props: Props) => {
record,
});
return children({
isLoading,
isLoading: loading,
defaultTitle,
resource,
basePath,
Expand Down
51 changes: 51 additions & 0 deletions packages/ra-core/src/controller/useGetOne.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { crudGetOne } from '../actions';
import { ReduxState, Record, Identifier } from '../types';
import useOptimisticQuery from './useOptimisticQuery';

export interface GetOneResponse {
data?: Record;
loading: boolean;
loaded: boolean;
error?: any;
}

/**
* @typedef GetOneResponse
* @type {Object}
* @property {Object} data
* @property {boolean} loading
* @property {boolean} loaded
* @property {Object} error
*/

/**
* Fetches a record by resource name and id and returns that record.
*
* Optimistically loads the record from the store if it was already fetched before.
*
* @example const { data } = useGetOne('posts', 123);
*
* @param {string} resource The resource name, e.g. "posts"
* @param {string|int} id the resource identifier, e.g. 123
* @param {object} meta the action meta (including side effects)
* @param {number} version An optional integer used to force fetching the record again
*
* @returns {GetOneResponse} An object with the shape { data, error, loading, loaded }
*/
const useGetOne = (
resource: string,
id: Identifier,
meta: any = {},
version: number
): GetOneResponse => {
return useOptimisticQuery(
crudGetOne(resource, id, meta),
(state: ReduxState) =>
state.admin.resources[resource]
? state.admin.resources[resource].data[id]
: null,
version
);
};

export default useGetOne;
73 changes: 73 additions & 0 deletions packages/ra-core/src/controller/useOptimisticQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useEffect } from 'react';
// @ts-ignore
import { useSelector, useDispatch } from 'react-redux';

import { ReduxState } from '../types';

export interface AsyncQueryResponse {
data?: any;
loading: boolean;
loaded: boolean;
error?: any;
}

export interface FetchAction {
type: string;
payload: any;
meta: {
fetch: string;
resource: string;
onSuccess?: any;
onFailure?: any;
};
}

/**
* @typedef AsyncQueryResponse
* @type {Object}
* @property {Object} data
* @property {boolean} loading
* @property {boolean} loaded
* @property {Object} error
*/

/**
* Uses an action to call the data provider
* and optimistically loads the result from the store.
*
* @example
*
* const { data, loading, loaded, error } = useOptimisticQuery(
* { type 'RA/GET_ONE', payload: { id: 123 }, meta: { fetch: GET_ONE, resource: 'posts' } }
* state => state.admin.resources.posts[123]
* );
*
* @param {object} action The action to dispatch, e.g. { type 'RA/GET_ONE', payload: { id: 123 }, meta: { fetch: GET_ONE, resource: 'posts' } }
* @param {function} selector The selector function to get the result from the store
* @param {number} version The version number. Increase to force a new fetch
*
* @returns {GetOneResponse} An object with the shape { data, error, loading, loaded }
*/
const useOptimisticQuery = (
action: FetchAction,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not so sure about the signature of this one. Should it accept:

  • an action returned by an action creator, as I did here, or
  • a quadruplet { type, resource, payload, meta } , like the useQuery action

In the latter case, we don't need the crud action creators anymore.

selector: (state: ReduxState) => string,
version: number = 1
) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(action);
}, [JSON.stringify({ action, version })]);
const data = useSelector(selector);
const { loading, loaded, error } = useSelector((state: ReduxState) => {
const key = JSON.stringify({
type: action.meta.fetch,
payload: action.payload,
});
return state.admin.requests && state.admin.requests[key]
? state.admin.requests[key]
: { loading: false, loaded: false };
});
return { data, loading, loaded, error };
};

export default useOptimisticQuery;
2 changes: 2 additions & 0 deletions packages/ra-core/src/reducer/admin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import record from './record';
import references, {
getPossibleReferenceValues as referencesGetPossibleReferenceValues,
} from './references';
import requests from './requests';
import saving from './saving';
import ui from './ui';
import auth, { isLoggedIn as authIsLoggedIn } from './auth';
Expand All @@ -19,6 +20,7 @@ export default combineReducers({
notifications,
record,
references,
requests,
saving,
ui,
auth,
Expand Down
Loading