向 dataProvider 中的 getList() 添加额外数据

问题描述 投票:0回答:1

对于我的react-admin项目,聚合是在服务器端(在ElasticSearch上)计算的。 API 发送回对象、总计以及聚合,这对于过滤很有用。

dataProvider 的

getList()
函数上的以下代码运行没有错误

export const dataProvider= {
  getList: async (resource:string, params:any) => {
    // Build url with filters, pages etc...
    const url = `${apiUrl}/${resource}?${stringify(query)}`;
    const { headers, json } = await httpClient(url);
    return ({
        data: json.objects,
        aggs: json.aggs, // <= here are the aggs I need for filtering
        total: json.total
    });
  },
  // other functions of the dataProvider ...
}

因此运行没有错误,但我的问题是:如何检索 API 返回的 aggs 数据?

here
所述,useListContext()钩子仅提供
data
total
,而不提供由
getList()

发回的附加值

到目前为止我看到的解决方案并不令人满意。

解决方案1

在 dataProvider 上定义一个额外的 getter,类似于

getAggs()
,但这会创建对 API 的额外(且不需要)调用

export const dataProvider= {
  getAggs: async (resource:string, params:any) => {
      const url = `${apiUrl}/${resource}?${stringify(query)}`;
      const { headers, json } = await httpClient(url);
      return ({
          data: json.aggs,
          total: json.total
      });
  },
  // other functions of the dataProvider ...
}

解决方案2

在 dataProvider 的

useStore()
中使用
getList()
,但这对我来说看起来有点脏。

export const dataProvider= {
  getList: async (resource:string, params:any) => {
    // Build url with filters, pages etc...
    const url = `${apiUrl}/${resource}?${stringify(query)}`;
    const { headers, json } = await httpClient(url);
    // temporarily store aggs in local storage
    const [aggs] = useStore('aggs', json.aggs); 
    return ({
        data: json.objects,
        total: json.total
    });
  },
  // other functions of the dataProvider ...
}

感谢您的帮助。

react-admin
1个回答
0
投票

我遇到了同样的问题。 除了

data
total
之外,唯一受尊重的属性是
pageInfo

一种丑陋的解决方法,但似乎有效的方法是将数据放在

pageInfo
属性下方。

export const dataProvider= {
  getList: async (resource:string, params:any) => {
    // Build url with filters, pages etc...
    const url = `${apiUrl}/${resource}?${stringify(query)}`;
    const { headers, json } = await httpClient(url);

    return ({
        data: json.objects,
        pageInfo: { aggs: json.aggs },
        total: json.total
    });
  },
  // other functions of the dataProvider ...
}
© www.soinside.com 2019 - 2024. All rights reserved.