2

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
  • In the child component render conditional return(props.data?(<div>whatever </div>):null) Commented Oct 8, 2020 at 16:10

1 Answer 1

4

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

3
  • In your code if length is 0 then it will render 0 on the screen
    – azium
    Commented Oct 8, 2020 at 16:13
  • @azium , thanks for pointing out, where's my usual not-not !! haha . just added. cheers! Commented Oct 8, 2020 at 16:15
  • commonly referred to as "double-bang" medium.com/better-programming/…
    – azium
    Commented Oct 8, 2020 at 16:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.