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>
)
}
The error "Rendered more hooks than during the previous render" occurs when we conditionally call a hook or return early before all hooks have ran. To solve the error, move all hooks at the top level of the function component and don't use hooks inside conditions.
What will happen when this useEffect Hook is executed, assuming name is not already equal to John? useEffect(() => { setName("John"); }, [name]); It will cause an error immediately. It will execute the code inside the function, but only after waiting to ensure that no other component is accessing the name variable.
The fix is simple. Just move the useEffect block before the if condition and the code should work fine.
useState() Hook is widely used in React applications to re-render the components on state changes. However, there are scenarios where we need to track state changes without re-rendering the components.
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With