I am trying to call an api through useEffect
until then I have set loading
true and if I get a response
or an error
I set it to false.
But I am getting an error if I try to do so.
Error:
Error: Rendered more hooks than during the previous render.
This error is located at:
in HomeScreen (created by SceneView)
in StaticContainer
in EnsureSingleNavigator (created by SceneView)
in SceneView (created by SceneView)
...
Code:
function HomeScreen({ navigation }) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const { authToken, logInfo, userData } = useContext(AuthContext);
const [token, setToken] = authToken;
const [isloggedIn, setIsLoggedIn] = logInfo;
const [userInfo, setUserInfo] = userData;
if (userInfo) {
useEffect(() => {
const isUserCreatedProfile = async (loggedInUserInfo, token) => {
try {
const apiHeaders = {
"User-Agent":
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0",
Accept: "application/json, text/plain, */*",
token: token,
};
await axios
.get(`${baseUrl}/api/user?email=${loggedInUserInfo["email"]}`, {
headers: apiHeaders,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
navigation.replace("CreateProfile", {
name: loggedInUserInfo["custom:Name"],
email: loggedInUserInfo["email"],
});
});
} catch (err) {
console.log(err);
}
};
setLoading(true);
isUserCreatedProfile(userInfo, token);
setLoading(false);
}, []);
}
return (
<SafeAreaView style={styles.container}>
{loading ? (
<ActivityIndicator color={colors.BorderColor} size="large" />
) : (
<Pressable
style={{ alignItems: "center", marginTop: 300 }}
onPress={async () => {
await AsyncStorage.removeItem("token");
console.log(
"token after delete:",
await AsyncStorage.getItem("token"),
);
setIsLoggedIn(false);
await Auth.signOut();
setToken(null);
setUserInfo(null);
}}
>
<Text style={styles.buttonTextStyle}>Logout</Text>
</Pressable>
)}
</SafeAreaView>
);
}
Why I am getting this error and how can I solve it?
CodePudding user response:
add useState to followings
const [token, setToken] = useState(authToken);
const [isloggedIn, setIsLoggedIn] = useState(logInfo);
const [userInfo, setUserInfo] = useState(userData);
Move if condition inside the useEffect
useEffect(() => {
if (userInfo) {
/// content
}
}, [userInfo])