Using Next.js and through useSWR I am pulling data from an endpoint every 30s using an automatic revalidation interval (https://swr.vercel.app/docs/revalidation#revalidate-on-interval). In the data that is being pulled, there is an array that on every pull will have between 1-4 more items since the last pull. How can I get the previous array.length and compare it to the new, revalidated array.length so that I have a variable that counts the differential?
The idea is to have the new items show up in an interval within those 30s. Suppose I have the array as 'messages', this is what I came to:
const prevMessagesLength = ?
const [message, setMessage] = useState(messages[0])
useEffect(() => {
let length = messages.length - prevMessagesLength
let delay = (30 / length) * 1000
for (var i = length; i >= 0; i--) {
showMessage(i)
}
function showMessage(i) {
setTimeout(function () {
setMessage(messages[i])
}, (length - i) * delay)
}
}, [messages])
https://swr.vercel.app/docs/api
Based on the offical document of swr, there's an option 'compare(a,b)' on useSWR hook.
This option is origianlly for comparing existing data and new data, the point is that you can access both data in this compare function.
I think you could use like this below