Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use props outside of render

I am trying to access my prop "post" from my parent. I can access it inside render(), but not above where I have my getCom(). How can I make the prop available in functions and not only in the render? I tried to use this.item.id.bind(this), but that does not work.

Parent:

<LoadComments post={item.id}/>

Child

class LoadComments extends Component {
  getCom = async () => {

    // Thid does not work

    this.unsubscribe = await firestore.collection("comments").where("post", "==", this.props.post).onSnapshot((querySnapshot) => {
     // Rest of code

  }
  render() {
    return (

      // This works:

      {this.props.post}

    )
  }
like image 399
vemund Avatar asked Mar 05 '23 10:03

vemund


1 Answers

To use the value of

 item.id

in your child component what you should do is:

In Parent:

<LoadComments post={item.id}>

In Child Component:

class LoadComments extends Component {

   async getCom(props) => {

   // This would work now

  this.unsubscribe = await firestore.collection("comments").where("post", "==", 
  props.post).onSnapshot((querySnapshot) => {
   // Rest of code

   }
  render() {
    const props = this.props;
      return (

        {this.props.post}

        getCom(props)

 )
}

You have to store the props in a static component in render method and then pass the props to the function declared outside the render method.

like image 147
Payel Dutta Avatar answered Mar 17 '23 05:03

Payel Dutta