如何每 X 秒刷新一次 React-Admin 列表数据? [英] How to refresh the React-Admin list data every X seconds?
问题描述
缓存文档 提到我可以向 dataprovider 添加代理,以便我的响应缓存 X 秒,而不是 React-Admin 在每次页面更改时刷新它们.但是,对于我的用例(股票交易应用程序),我希望每 1 秒从我的 API 为我的列表视图获取新数据.我希望通过使用上述缓存方法来做到这一点,但看起来如果用户在页面上时缓存过期,页面将不会自动刷新.
The cache documentation mentions that I can add a proxy to the dataprovider so that my responses are cached for X seconds, rather than React-Admin refreshing them on every page change. However, for my use case (a stock trading app), I'd like to get fresh data from my API for my listview every 1 second. I was expecting to do this by using the above cache method, but it looks like if the cache expires while the user is on a page, the page won't automatically refresh.
如何让我的 React-Admin 列表视图每 X 秒刷新一次,或者在缓存到期时自动刷新?
How can I get my React-Admin list view to refresh either every X seconds, or automatically on cache expiry?
推荐答案
要定期更新列表视图,您可以使用:useRefresh()
from React-Admin 和 useRecursiveTimeout()
从这里:
https://www.aaron-powell.com/posts/2019-09-23-recursive-settimeout-with-react-hooks/
To periodically update the List View, you can use: useRefresh()
from React-Admin and useRecursiveTimeout()
from here:
https://www.aaron-powell.com/posts/2019-09-23-recursive-settimeout-with-react-hooks/
import React, { useEffect, useRef } from 'react';
import { List, useRefresh } from 'react-admin';
function useRecursiveTimeout(callback, delay) {
const savedCallback = useRef(callback)
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
let id
function tick() {
const ret = savedCallback.current()
if (ret instanceof Promise) {
ret.then(() => {
if (delay !== null) {
id = setTimeout(tick, delay)
}
})
} else {
if (delay !== null) {
id = setTimeout(tick, delay)
}
}
}
if (delay !== null) {
id = setTimeout(tick, delay)
return () => id && clearTimeout(id)
}
}, [delay])
}
const MyList = (props) => {
const refresh = useRefresh()
useRecursiveTimeout(() => refresh(), 1000)
return (
<List>
...
</List>
)
}
这篇关于如何每 X 秒刷新一次 React-Admin 列表数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!