5

Is it possible to implement a custom request type in a custom provider in the react-admin framework?

My Use Case

In my case I have 2 separate cases of reference fields.

1. Reference ID field (normal)

api -> users/1
api -> comments/1

2. Sub Entity Reference

api -> users/1/comments/1

So I was planning to implement another request type, like this:

    switch (type) {
      case GET_LIST:
        return apiGetList(resourceName, params);
      case GET_MANY:
        return apiGetMany(resourceName, params);
      case GET_MANY_REFERENCE:
        return apiGetManyReference(resourceName, params);
      case GET_MANY_REFERENCE_CUSTOM:
        return apiGetManyReferenceCustom(resourceName, params);
    }

But I can't figure out how to trigger the type from the custom field?

Ben Winding
  • 10,208
  • 4
  • 80
  • 67

1 Answers1

0

Update for react-admin 3.x

So with React Admin 3.x the data provider now uses method calls instead of a switch case.

For example you can create your own dataprovider method, and the consumer can check if it exists by calling it.

  try {
    const response = await dataProvider.createMany(resource, { data: values });
    return response;
  } catch (error) {
    const shouldTryFallback = error.toString().includes("Unknown dataProvider");
    const apiError = !shouldTryFallback;
    if (apiError) {
      // handle api error
    }
    if (shouldTryFallback) {
      console.log(
        "createInDataProvider",
        "createMany not found on data provider (you may need to implement it)"
      );
      try {
        // try and use fallback dataprovider methods
      } catch (error) {
        // handle fallback error
      }
    }
  }
  return reportItems;

Full example of how this is used: https://github.com/benwinding/react-admin-import-csv/blob/0868ca554501c3545dac28a5101ee60a20736aa2/src/uploader.ts#L78

Ben Winding
  • 10,208
  • 4
  • 80
  • 67