2

I need to implement async/await with useEffect React hook. I tried a lot of ways. Every time i have an error: Hooks can only be called inside the body of a function component.

import React, { useEffect } from 'react'
import { ActivityIndicator, StatusBar, StyleSheet, View } from 'react-native'
import * as Keychain from 'react-native-keychain'
import useEffectAsync from '../utils'

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center'
  }
})

const AuthLoadingScreen = ({ navigation }) => {
  useEffect(() => {
    const fetchData = async () => {
      const data = await Keychain.getGenericPassword()
      console.log('data', data)
      navigation.navigate(data ? 'App' : 'Auth')
    }
    fetchData()
  }, [])

  const { container } = styles
  return (
    <View style={container}>
      <ActivityIndicator />
      <StatusBar barStyle="default" />
    </View>
  )
}

export { AuthLoadingScreen }

skyboyer
  • 22,209
  • 7
  • 57
  • 64
jocoders
  • 1,594
  • 2
  • 19
  • 54

2 Answers2

2

Everything looks good, but try this also,

export const AuthLoadingScreen = ({ navigation }) => {...}

Or

const AuthLoadingScreen = ({ navigation }) => {...}

export default AuthLoadingScreen;

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
  • 1
    Thank you so much for the answer. Your decision has worked for me! But why its different behavior if i export by not default it is not working? – jocoders Jul 12 '19 at 05:50
  • This is wrong - `export { AuthLoadingScreen }` you cannot export component like this, component either exported `default` or `named`. – ravibagul91 Jul 12 '19 at 06:02
  • But how about spaghetti code when you need to import many components from the one folder? – jocoders Jul 12 '19 at 10:07
  • For that you should do this - `export const combinedComponents = { component1, component2,....}` – ravibagul91 Jul 12 '19 at 10:09
1

I would wrap it in an anonymous function and have it called immediately:

I might try this:

const AuthLoadingScreen = ({ navigation }) => {
  useEffect(() => {
   (async () => {
      const data = await Keychain.getGenericPassword()
      console.log('data', data)
      navigation.navigate(data ? 'App' : 'Auth')
    })()

  }, [])

  const { container } = styles
  return (
    <View style={container}>
      <ActivityIndicator />
      <StatusBar barStyle="default" />
    </View>
  )
}

If it worked, do let me know because I am learning React Hooks as well :D.

  • Thank you so much for the answer, but the deal was in the right export. My decision has worked only with export default AuthLoadingScreen – jocoders Jul 12 '19 at 06:05
  • @jocoders thanks a lot for the feedback. As I am also learning hooks, it was really helpful knowing the correct solution. – Comfort Ajala Jul 12 '19 at 09:22