“Rendered more hooks than during the previous render” error when the initial value for the hook is a query result from a database

爱⌒轻易说出口 提交于 2020-05-17 06:08:23

问题


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>
    )
}

回答1:


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>
    )
}


来源:https://stackoverflow.com/questions/59339287/rendered-more-hooks-than-during-the-previous-render-error-when-the-initial-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!