10

I'm using React's hook and I want to have a value that is retrieved from the database as the initial value. However, I'm getting the following error:

Invariant Violation: Invariant Violation: Rendered more hooks than during the previous render.

const { data, loading, error } = useQuery(GET_DATA)
const { initialValue } = data
const [value, setValue] = useState(initialValue)

I'm using the React Apollo hook.

Update

export default NotificationScreen = ({ navigation }) => {
    const { data: initialNotificationSettings, loading: loadingInitialSettings, error: initialSettingsError } = useQuery(GET_NOTIFICATION_SETTINGS)
    if (loadingInitialSettings) {
        return (
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#FF5D4E" />
            </View>
        )
    }
    if (initialSettingsError) return <Text>Error...</Text>

    const {
        borrowerLendingNotificationToken,
    } = initialNotificationSettings.me
    const [borrowerPending, notifyBorrowerPending] = useState(borrowerLendingNotificationToken)

    return (
        <SafeAreaView style={styles.container}>
        </SafeAreaView>
    )
}
Kevvv
  • 3,655
  • 10
  • 44
  • 90

1 Answers1

29

The problem is that you are using hook below return. Try to update

export default NotificationScreen = ({ navigation }) => {
    const { data: initialNotificationSettings, loading: loadingInitialSettings, error: initialSettingsError } = useQuery(GET_NOTIFICATION_SETTINGS)

    const [borrowerPending, notifyBorrowerPending] = useState("")

    useEffect(() => {
        if (initialNotificationSettings.me) {
            const { borrowerLendingNotificationToken } = initialNotificationSettings.me
            notifyBorrowerPending(borrowerLendingNotificationToken);
        }
    }, [initialNotificationSettings]);

    if (loadingInitialSettings) {
        return (
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#FF5D4E" />
            </View>
        )
    }
    if (initialSettingsError) return <Text>Error...</Text>

    return (
        <SafeAreaView style={styles.container}>
        </SafeAreaView>
    )
}
Tuan Luong
  • 3,902
  • 1
  • 16
  • 18