Search code examples
reactjsreact-admin

How to connect to nested paths in React-admin? (e.g. http://my.api.to/users/active)


I have API paths like http://my.api.to/user/active where /user is a working api call as well as /user/active.

How should I add them to < Resource name="" >, so my dataProvider accepts it?

I use the default ra-data-json-server's dataprovider with minor changes.

my GET_LIST looks like this:

        case GET_LIST: {
            const { page, perPage } = params.pagination;
            const { field, order } = params.sort;
            const query = {
                ...fetchUtils.flattenObject(params.filter),
                //filter: JSON.stringify(params.filter),
                sort: field,
                order: order,
                start: (page - 1) * perPage,
                end: page * perPage,
            };
                url = `${apiUrl}/${resource}?${stringify(query)}`;
            }
            break;
        }

I also tried to tweak the url based on the resource name without any luck:

        case GET_LIST: {
            const { page, perPage } = params.pagination;
            const { field, order } = params.sort;
            const query = {
                ...fetchUtils.flattenObject(params.filter),
                //filter: JSON.stringify(params.filter),
                sort: field,
                order: order,
                start: (page - 1) * perPage,
                end: page * perPage,
            };
            if (resource === 'clicks/monthly'){
                url = `${apiUrl}/clicks/monthly?year=2019&${stringify(query)}`;
            } else {
                url = `${apiUrl}/${resource}?${stringify(query)}`;
            }
            break;
        }

Can you please help?


Solution

  • Try naming your resource without a slash, for example users-active

      <Admin
            dataProvider={jsonServerProvider('http://my.api.to')}
            dashboard={Dashboard}
        >
             <Resource name="users" icon={UserIcon} list={UserList}  options={{ label: 'All users' }}/>
             <Resource name="users-active" icon={UserIcon} list={UserList} options={{ label: 'Active users' }}/>
        </Admin>
    

    In your dataprovider, you'll then be able to route the call as you want:

         case GET_LIST: {
            const { page, perPage } = params.pagination;
            const { field, order } = params.sort;
            const query = {
                ...fetchUtils.flattenObject(params.filter),
                //filter: JSON.stringify(params.filter),
                sort: field,
                order: order,
                start: (page - 1) * perPage,
                end: page * perPage,
            };
            if (resource === 'users-active'){
                    url = `${apiUrl}/users/active?${stringify(query)}`;
                } else {
                    url = `${apiUrl}/${resource}?${stringify(query)}`;
            }
            break;
        }