I've created application with BottomNavigation
from React Native Paper.
App.tsx:
const App = () => {
const colorScheme = Appearance.getColorScheme()
const isDarkTheme = colorScheme === 'dark'
const theme = isDarkTheme ? CombinedDarkTheme : CombinedDefaultTheme
const [index, setIndex] = React.useState(0)
const [routes] = React.useState([
{key: 'home', icon: 'home'},
{key: 'map', icon: 'compass'},
{key: 'post', icon: 'plus-box'},
{key: 'chat', icon: 'forum'},
{key: 'profile', icon: 'account'},
])
const api: IApiGateway = new ApiGateway()
const getPostsUseCase: GetPostsUseCase = new GetPostsInteractor(api)
const renderScene = BottomNavigation.SceneMap({
home: () =>
HomeScreen({
getPostsUseCase: getPostsUseCase,
}),
map: MapScreen,
post: PostScreen,
chat: ChatScreen,
profile: ProfileScreen,
})
return (
<PaperProvider theme={theme}>
<BottomNavigation
labeled={false}
navigationState={{index, routes}}
onIndexChange={setIndex}
renderScene={renderScene}
activeColor="#ff5500"
/>
</PaperProvider>
)
}
HomeScreen.tsx:
const HomeScreen = ({getPostsUseCase}: Props) => {
const [isLoading, setLoading] = useState(true)
const [data, setData] = useState<Post[]>([])
useEffect(() => {
getPostsUseCase
.execute({
limit: 15,
since: null,
})
.then((page: Page<Post>) => {
setData(page.data)
})
.catch((error: string) => console.error(error))
.finally(() => setLoading(false))
}, [getPostsUseCase])
return (
<SafeAreaView style={styles.frame}>
{isLoading ? (
<Text>Loading...</Text>
) : (
<FlatList
style={styles.list}
data={data}
renderItem={NewsPost}
keyExtractor={item => item.id.toString()}
/>
)}
</SafeAreaView>
)
}
It works but when I switch to another tab (not Home), the HomeScreen
sends requests to the backend again and again, as many times as I switch between tabs.
I am a noobie in React Native and even in React... How to unmount inactive component or prevent the loading on tab switching? Why does it happen?