0

I have a function from where I want to return JSX. I´m new to React, I tried this: history is array of objects and I want to return text from it and display it.

renderCard = () => { const db = firebase.firestore();

db.collection("users")
  .doc(firebase.auth().currentUser.uid)
  .collection("userRequestDeposit")
  .get()
  .then(snapshot => {
    let history = snapshot.docs.map(doc => {
      const data = doc.data().request;
      return { ...data };
    });
 

    history.forEach(elem => {
      return (
        <View>
          <Text>{elem.data}</Text>
        </View>
      );
    });
  });

};

1
  • foreach doesn't return anything, try store this array in a variable and return this variable Commented Apr 29, 2021 at 19:51

1 Answer 1

1

So this is a nice case study for how to use React.

You want to fetch this data when the component mounts. When you have the data, you will update the component's state. You can then render the output from that state.

Here is how you could do this with your code:

import {useEffect, useState} from 'react';

const YourComponent = () => {
  const [history, setHistory] = useState([]); // Store your data in this state

  // this useEffect will run only once (when the component mounts). 
  useEffect(() => {
    db.collection('users')
      .doc(firebase.auth().currentUser.uid)
      .collection('userRequestDeposit')
      .get()
      .then(snapshot => setHistory(snapshot.docs.map(doc => ({...doc.data().request}))));
  }, []); // <-- the empty dependency array means it only runs on mount

  // when history is updated, you can map over the array and render the output here
  return history.map(item => (
    <View key={item.id}>
      <Text>{item.data}</Text>
    </View>
  ));
};

or as a class component...

import {Component} from 'react';

class YourComponent extends Component {
  state = {
    history: [],
  };

  componentDidMount() {
    db.collection('users')
      .doc(firebase.auth().currentUser.uid)
      .collection('userRequestDeposit')
      .get()
      .then(snapshot => {
        this.setState({history: snapshot.docs.map(doc => ({...doc.data().request}))});
      });
  }

  render() {
    return history.map(item => (
      <View key={item.id}>
        <Text>{item.data}</Text>
      </View>
    ));
  }
}

Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Is there an equivalent for class based components?
I've updated the answer with the class component equivalent

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.