'React native - Error: Hooks can only be called inside of a function component
I have the following problem in my component "SubmitButton" I want to execute a custom hook by clicking on the button. This hook is called "useLogin".
But currently I always get the following error message: "Invalid hook call. Hooks can only be called inside of the body of a function component."
Can anyone tell me where my error is or what I am not understanding correctly?
SubmitButton Code:
import React from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import useLogin from "../../../../app/hooks/useLogin";
import { useSelector } from "react-redux";
const SubmitButton = () => {
const email = useSelector((state) => state.login.email);
const password = useSelector((state) => state.login.password);
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => useLogin({ email, password })}
>
<Text style={styles.text}>Anmelden</Text>
</TouchableOpacity>
</View>
);
};
useLogin Code:
import api from "../api/config";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import * as SecureStore from "expo-secure-store";
import { setJwtToken } from "../redux/features/auth/loginSlice";
export default function useLogin ({email, password}) {
const dispatch = useDispatch();
useEffect(() => {
login({email, password});
}, []);
const login = async ({ email, password }) => {
try {
const response = await api.post("/users/login", { email, password });
if (response.status === 200) {
dispatch(setJwtToken(response.data.token));
await SecureStore.setItemAsync("jwtToken", response.data.token);
}
}
catch(e) {
console.log(e);
}
};
}
Solution 1:[1]
you need to pass useLogin() to a variable ( like const dispatch = useDispatch() ) then use the variable like a function just like dispatch().
import React from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import useLogin from "../../../../app/hooks/useLogin";
import { useSelector } from "react-redux";
const SubmitButton = () => {
const email = useSelector((state) => state.login.email);
const password = useSelector((state) => state.login.password);
const loginHook = useLogin();
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => loginHook({ email, password })}
>
<Text style={styles.text}>Anmelden</Text>
</TouchableOpacity>
</View>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mohammad farhadi |