'Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`Home_Profile`)

I get this error while trying to navigate between screens with react native stack navigator. I think this was working in my previous project which had react 17.0.1 and react native 0.64.2, this project is react 17.0.2 and react native 0.66.4, helps would be appreciated.

log

Warning: Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`Home_Profile`). To locate the bad setState() call inside `Home_Profile`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

error comes when I try to call navigation in an onPress prop on a Flatlist render item component.

renderItem={({ item }) => (
  <View style={{ backgroundColor: "#f6f6f6" }}>
     <PostCard
        item={item}
        onPress={() => navigation.navigate("Home_Profile")}
     />
  </View>
)}
const PostCard = ({ item, onPress }) => {
  
  React.useEffect(() => {
    async function fetchUserData() {
      const data = await getUserData(item.userid);
      setProfileimg(data.userimg);
      setName(data.name);
      setLocation(data.location);
    }
    fetchUserData();
  }, []);

  return (
        <TouchableOpacity onPress={onPress}>
            <Text
                style={{
                    color: "#231454",
                    fontWeight: "bold",
                    fontSize: 15,
                    marginBottom: 3,
                }}
            >
                {name}
            </Text>
        </TouchableOpacity>
  )      
};

export default PostCard;

Home_Profile

import React from "react";
import { View, Text, Button } from "react-native";

const Home_Profile = ({ navigation }) => {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>Home_Profile.js</Text>
      <Button title="back" onPress={navigation.navigate("Home")} />
    </View>
  );
};

export default Home_Profile;


Solution 1:[1]

I found the cause of the problem, when you render the second screen, it is executing the onPress method of the button that goes back home, and that navigation causes the render method in that home screen to execute, which means you are trying to execute two renders at the same time, to fix that, just add an arrow function to the navigate home function as shown bellow:

onPress={()=>{navigation.navigate("Home")}}

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 valn1 XD