cant pass react state to a child after setState()?

Viewed 111

I'm working on reactjs project

where I fetching data from firestore and set the app.js state to the fetched data, and I pass this state to a child of app.js to display it but it's undefined at first then it consoles the right state.

How can I make the child component render only after its props is correct?!

  fetchDataFromFirestore = async () => {
    let dataRefFromFirestore = database.doc('items/fruitsDataJsonFile');
    (await dataRefFromFirestore).onSnapshot((snapshot) => {
      let fetchedItems = snapshot.data();
      this.setState({
        fetchedItems: fetchedItems.data
      },
        console.log('DONEEE ADIING'))
    })
  }

1 Answers

You can use a concept called "Conditional Rendering".

It will be like

    {!!this.state.fetchedItems?.length && 
<YourChildComponent fetchedItems={this.state.fetchedItems}>

Then, your child component will be rendered only when the state has array data.

Similarly, your child component will have props called fetchedItems with full data.

Reference: https://reactjs.org/docs/conditional-rendering.html

Related