0

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?

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123

1 Answers1

1

You are firing the homefunction App.tsx everytime.

home: () =>

const renderScene = BottomNavigation.SceneMap({
home: () =>
  HomeScreen({
    getPostsUseCase: getPostsUseCase,
  }),
Gismo1337
  • 279
  • 1
  • 18
  • To be honest, I used it because I couldn't find in their docs how to pass arguments into tab components. How to pass arguments in right way? – Denis Sologub Feb 23 '22 at 22:46
  • 1
    https://stackoverflow.com/questions/60439210/how-to-pass-props-to-screen-component-with-a-tab-navigator – Gismo1337 Feb 23 '22 at 22:55