Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error: Rendered more hooks than during the previous render in react native

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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?

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading