对于我的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 ...
}
感谢您的帮助。
我遇到了同样的问题。 除了
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 ...
}