0

Obtaining data from firestore and trying to render in a table with reactJS I can not render it. Does anyone know if I have an error?

This is my code:

state = {
    items:[]
};

componentDidMount(){
    db.collection('items').get().then((snapShot) => {
        snapShot.docs.map( doc => {
           this.state.items.push({ id: doc.id, data: doc.data()});
        })
   }, error => {
       console.log(error)
   }); 
};

Table

render() {
    const { items, inputValue } = this.state;
    console.log(items)
    return (
        <React.Fragment>
            <Table hover className="text-center">
                <thead>
                <tr>
                    <th>Name</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
                </thead>
                <tbody>  
                    { items && items !== undefined ? items.map((item, key) => (
                        <tr><td>{item.data.item}</td></tr>
                     )): null }
                </tbody>
             </Table>
        </React.Fragment>
    )
  }

Making a console.log of this.state.items I get the data like this:

0:{id: "1NDr66bsRosASM7qYCJb", data: {…}}
1:{id: "2k0DKLVBlPxZDIQt7KPx", data: {…}}
2:{id: "4cADNojHNXqkFcnl52jw", data: {…}}

And using map I can not access the data.

Can you help me, please? Thank you

2
  • 1
    this.state.items.push do not modify state object directly. Use setState method. Commented Aug 28, 2018 at 6:24
  • @YuryTarabanko I do not know how I forgot that! Thank you!!! Commented Aug 28, 2018 at 6:29

1 Answer 1

3

In componentDidMount() you have to set your state.

componentDidMount(){
    db.collection('items').get().then((snapShot) => {
       this.setState({
       items:snapShot.docs.map( doc => {
           return { id: doc.id, data: doc.data()}               
        });
       });
   }, error => {
       console.log(error)
   }); 
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.