Toni
Toni

Reputation: 21

How to use props within UseEffect of the child component?

I want the Child Component to fetch a Firebase Collection based on the props i passed through the parent. The problem is that when i try to fetch my props in the UseEffect() of my Child Component it is undefined.

I`ve tried

export default function Parent(){

  const [activeUser, setActiveUser] = useState();
  const [users, setUsers] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  
  const fetchUsers = async () => {
    let tempUsers = [];
    await Firebase.firestore().collection('users').get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        tempUsers.push({
          id: doc.id,
          data: doc.data(),
        })
      });
    })
    setUsers(tempUsers);      
  }

  useEffect(() => {
    fetchUsers().then(() => {
      setActiveUser(users[0]);
      setIsLoading(false);
    })
  },[]);
  
  if(isLoading){
    <View>
      <Text>Loading...</Text>
    </View>
  }else{
    return (
      <View>
        <Child user={activeUser} />
      </View>
    )
  }   
}

export default function Child(props){
      
  useEffect(() => {
        console.log(props.user)
  }, []) // I even tried something like [props | props.user] but nothing helped :/

  ...

   }

Why is my props.user undefined?

Upvotes: 0

Views: 714

Answers (2)

pepinillo6969
pepinillo6969

Reputation: 463

Try adding users as a dependecy in useeffect of parent function and props.user as dependecy in useeffect of child.

Upvotes: 0

LeadDreamer
LeadDreamer

Reputation: 3499

Very likely because useEffect() is SYNCHRONOUS and your fetchUser() is ASYNCHRONOUS. You will need to put the fetchUsers() call in a closure within the useEffect() to allow it to complete, and you need to make your child tolerant of user being undefined until the result comes in. Also note there is no guarantee of the ORDER that SetActiveUser() and SetIsLoading() will apply.

Upvotes: 1

Related Questions