Poll periodically for new posts

This commit is contained in:
Paul Frazee 2022-11-17 12:33:19 -06:00
parent f6e591339d
commit eae5ac839c
5 changed files with 89 additions and 3 deletions

View file

@ -1,13 +1,15 @@
import React, {useState, useEffect, useMemo} from 'react'
import {View} from 'react-native'
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import useAppState from 'react-native-appstate-hook'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {ViewHeader} from '../com/util/ViewHeader'
import {Feed} from '../com/posts/Feed'
import {FAB} from '../com/util/FloatingActionButton'
import {useStores} from '../../state'
import {FeedModel} from '../../state/models/feed-view'
import {ScreenParams} from '../routes'
import {s} from '../lib/styles'
import {s, colors} from '../lib/styles'
export const Home = observer(function Home({
visible,
@ -15,6 +17,9 @@ export const Home = observer(function Home({
}: ScreenParams) {
const store = useStores()
const [hasSetup, setHasSetup] = useState<boolean>(false)
const {appState} = useAppState({
onForeground: () => doPoll(true),
})
const defaultFeedView = useMemo<FeedModel>(
() =>
new FeedModel(store, 'home', {
@ -23,9 +28,24 @@ export const Home = observer(function Home({
[store],
)
const doPoll = (knownActive = false) => {
if ((!knownActive && appState !== 'active') || !visible) {
return
}
if (defaultFeedView.isLoading) {
return
}
console.log('Polling home feed')
defaultFeedView.checkForLatest().catch(e => {
console.error('Failed to poll feed', e)
})
}
useEffect(() => {
let aborted = false
const pollInterval = setInterval(() => doPoll(), 15e3)
if (!visible) {
console.log('hit')
return
}
if (hasSetup) {
@ -40,6 +60,7 @@ export const Home = observer(function Home({
})
}
return () => {
clearInterval(pollInterval)
aborted = true
}
}, [visible, store])
@ -53,6 +74,10 @@ export const Home = observer(function Home({
const onPressTryAgain = () => {
defaultFeedView.refresh()
}
const onPressLoadLatest = () => {
defaultFeedView.refresh()
scrollElRef?.current?.scrollToOffset({offset: 0})
}
return (
<View style={s.flex1}>
@ -64,7 +89,34 @@ export const Home = observer(function Home({
style={{flex: 1}}
onPressTryAgain={onPressTryAgain}
/>
{defaultFeedView.hasNewLatest ? (
<TouchableOpacity style={styles.loadLatest} onPress={onPressLoadLatest}>
<FontAwesomeIcon icon="arrow-up" style={{color: colors.white}} />
<Text style={styles.loadLatestText}>Load new posts</Text>
</TouchableOpacity>
) : undefined}
<FAB icon="pen-nib" onPress={onComposePress} />
</View>
)
})
const styles = StyleSheet.create({
loadLatest: {
flexDirection: 'row',
position: 'absolute',
left: 10,
bottom: 15,
backgroundColor: colors.pink3,
paddingHorizontal: 10,
paddingVertical: 8,
borderRadius: 30,
shadowColor: '#000',
shadowOpacity: 0.3,
shadowOffset: {width: 0, height: 1},
},
loadLatestText: {
color: colors.white,
fontWeight: 'bold',
marginLeft: 5,
},
})