Data retrieved from firebase cannot be displayed in jsx in React

Asked 2 years ago, Updated 2 years ago, 249 views

I want to display the data obtained from firebase in react component, but it returns undefined and does not display well.I don't think the data is synchronized well from the perspective of the life cycle. Could someone please let me know?

class Grammer extensions React.Component {
    
    state= 
        {
         N1: [ ],
         N2: [ ],
         N3: [ ]
        };

    componentDidMount(){
       const fetchData=()=>{
        firebase.database().ref("N3")
            .on(("value"), (snapshot)=>{
                snapshot.forEach(childSnapshot)=>{
                    This.setState(()=>{
                        N3—this.state.N3.push({
                        id —childSnapshot.key,
                        ...childSnapshot.val()
                        })
                    });
                });
                console.log (this.state.N3[0])
            });
    };
    fetchData();
};

    render() {
        
        if(!this.state.N3[0]){
            return<div>Loading</div>
        } else if(this.state.N3[0]){
           return(
                <div>
                    <N3Grammer N3={this.state.N3}/>
                </div>
            )
        }
    }
};

javascript reactjs firebase

2022-09-30 21:51

1 Answers

The acquisition process is asynchronous, so componentDidMount ends before retrieving and settingState data. I think it's Render.
If you wait for Promise or async, wait for the acquisition process to complete, it will be reflected.

[Additional note]
It is difficult to write the source part in the comments, so I will edit it in the answer.
As you said, componentWillMount is deprecated, so
I will list the version using hooks below, so please refer to it

const db=firebase.firestore();

export default() = > {
  const[list, setList] = useState([]);

  useEffect(()=>{
    const fetchData=async()=>{
      const ref = db.collection("list");
      const snapShot = wait ref.get();
      constlist=snapShot.docs.map(doc)=>{
        constitem=doc.data();
        item.id = doc.id;
        return item;
      });
      setList(list);
    };
    fetchData();
  }, []);

  return(
    <div>
      {list.map((item)=>(
        <div key={item.id}>{item.id}</div>
      ))}
    </div>
  );
};


2022-09-30 21:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.